Getting JSON value from HTTP Request using GSON with Java - java

I need to get the lat and lng cords as separate string values. I decided to use GSON to help with this but am having issues getting the points. I'd prefer not to add any extra classes but it's not a deal breaker. I don't even care to use an easier solution without GSON if there is one.
Below is what I tried.
private static String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject json = new JSONObject(jsonText);
return json;
} finally {
is.close();
}
}
public static void main(String[] args) throws InterruptedException, IOException, JSONException {
JSONObject json = readJsonFromUrl("http://open.mapquestapi.com/geocoding/v1/address?key=Fmjtd|luu821ual9,8w=o5-94aaqy&location=1448south4thstreetlouisvilleky");
System.out.println(json.toString());
System.out.println(json.get("results"));
}
I can get the results string but not just the lat or lng. Plus it uses extra classes I was trying to avoid. Below is what the JSON returned from the URL looks like.
{
"info": {},
"options": {},
"results": [
{
"providedLocation": {
"location": "address here"
},
"locations": [
{
"street": "address here",
"adminArea6": "",
"adminArea6Type": "Neighborhood",
"adminArea5": "city name",
"adminArea5Type": "City",
"adminArea4": "County name",
"adminArea4Type": "County",
"adminArea3": "State name",
"adminArea3Type": "State",
"adminArea1": "US",
"adminArea1Type": "Country",
"postalCode": "zip here",
"geocodeQualityCode": "P1AAX",
"geocodeQuality": "POINT",
"dragPoint": false,
"sideOfStreet": "N",
"linkId": "0",
"unknownInput": "",
"type": "s",
"latLng": {
"lat": 90.227222,
"lng": -90.762007
},
"displayLatLng": {
"lat": 90.227222,
"lng": -90.762007
},
"mapUrl": "http://open.mapquestapi.com/staticmap/v4/getmap?key=111111111,160&pois=purple4"
}
]
}
]
}

JsonParser parser = new JsonParser();
JsonObject o = parser.parse(jsonStr).getAsJsonObject();
JsonElement latLng = o.get("results")
.getAsJsonArray().get(0)
.getAsJsonObject().get("locations")
.getAsJsonArray().get(0)
.getAsJsonObject().get("latLng");
Parse json String as Jsonobject, and get value one by one. but I think the fastest way is creating a model to map the Json String Object.

Related

Map JSON array into java object array

I'm calling API and getting the response as a JSON array I need to map that array into Java object array. Here I've defined the model class below you can see API JSON array, Model class and the way I try to map JSON array into Java object array. I need to make sure if this approach is correct or not.
API response JSON array
[
{
"sanctionId": 594,
"listId": "SDN",
"listType": "SANCTION",
"publisher": "OFAC",
"addedDate": "2022-02-11T04:52:59.775+0000",
"programs": "CUBA",
"name": " CUBA CIGARS TRADE",
"title": null,
"type": "Entity",
"contacts": [
{
"id": 361,
"address": " ",
"city": "",
"state_province": "",
"country": "Italy",
"remarks": null
}
],
"identities": null,
"remarks": null,
"other": null,
"score": 2.1659167
},
{
"sanctionId": 602,
"listId": "SDN",
"listType": "SANCTION",
"publisher": "OFAC",
"addedDate": "2022-02-11T04:52:59.779+0000",
"programs": "CUBA",
"name": " CUBA N CIGARS TRADE",
"title": null,
"type": "Entity",
"contacts": [
{
"id": 361,
"address": " ",
"city": "",
"state_province": "",
"country": "Italy",
"remarks": null
}
],
"identities": null,
"remarks": null,
"other": null,
"score": 1.9129416
}
]
Model Class(here I've omitted getters and setters) :
public class SanctionInquiryResponse {
private String sanctionId="";
private String listId="";
private String listType="";
private String publisher="";
private String addedDate="";
private String programs="";
private String name="";
private String title="";
private String type="";
private String identities="";
private String remarks="";
private String other="";
private String score="";
private List<Contacts> contacts = null;
}
public class Contacts {
private String id = "";
private String address = "";
private String city = "";
private String state_Province = "";
private String country = "";
private String remarks = "";
}
Here is the way I'm trying to map the JSON array into the Java object array
String url="http://localhost:8070/getObject";
ObjectMapper mapper = new ObjectMapper();
//String jsonInString = mapper.writeValueAsString(openCaseRequest);
Client client = Client.create();
client.setConnectTimeout(120*1000);
client.setReadTimeout(120*1000);
WebResource webResource = client.resource(url);
ClientResponse response = webResource.type(MediaType.APPLICATION_JSON).post(ClientResponse.class);
String output = response.getEntity(String.class);
JSONArray jsonArray = new JSONArray(output);
Gson gson = new Gson();
for (int i = 0; i < jsonArray.length(); i++) {
sanctionInquiryResponse = gson.fromJson(jsonArray.getJSONObject(i).toString() ,SanctionInquiryResponse.class);
}

Not able to print json object in a json array

This is the json I'm working with. I need to print description object which is inside weather array. I am getting JSONArray[2] not found exception while compiling. I'm using java-json.
{
"coord": {
"lon": 72.85,
"lat": 19.01
},
"weather": [
{
"id": 721,
"main": "Haze",
"description": "haze",
"icon": "50n"
}
],
"base": "stations",
"main": {
"temp": 303.15,
"pressure": 1009,
"humidity": 74,
"temp_min": 303.15,
"temp_max": 303.15
},
"visibility": 3000,
"wind": {
"speed": 2.1,
"deg": 360
},
"clouds": {
"all": 20
},
"dt": 1539273600,
"sys": {
"type": 1,
"id": 7761,
"message": 0.0642,
"country": "IN",
"sunrise": 1539219701,
"sunset": 1539262109
},
"id": 1275339,
"name": "Mumbai",
"cod": 200
}
this is the code--
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONObject;
import org.json.JSONArray;
class Send_HTTP_Request2 {
public static void main(String[] args) {
try {
Send_HTTP_Request2.call_me();
} catch (Exception e) {
e.printStackTrace();
}
}
static void call_me() throws Exception {
String url = "http://api.openweathermap.org/data/2.5/weather?id=1275339&APPID=77056fb4e0ba03b117487193c37c90d2";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
JSONObject myResponse = new JSONObject(response.toString());
JSONArray jrr= myResponse.getJSONArray("weather");
System.out.println("CITY-"+myResponse.getString("name"));
JSONObject desc = jrr.getJSONObject(2);
System.out.println(desc);
}
}
For the JSONArray method of getJSONObject(int index) (Link to the Javadoc here)
You're right to grab the JSONObject inside of the array, but you're grabbing the wrong index, which in this case, is 0 since in Java, index 0 is the first item of the array. (More on Arrays and indexes here)
And then you would just call desc.getString("description") and assign it to a String, since the description key is a String type.
So more specifically you'd do something link this (assuming we're not checking for nulls or iterating through the array with a for loop or anything):
JSONObject myResponse = new JSONObject(response.toString());
JSONArray jrr= myResponse.getJSONArray("weather");
System.out.println("CITY-"+myResponse.getString("name"));
JSONObject weatherObj = jrr.getJSONObject(0);
String desc = weatherObj.getString("description");
System.out.println(desc);
Hope this helps!
Edited for formatting

How to extract key value from a JSON response in Java Language? I want to extract the value of "doj" but I'm not able to do so

{
"reservation_upto": {
"lng": 78.0098161,
"lat": 27.1752554,
"code": "AGC",
"name": "AGRA CANTT"
},
"debit": 3,
"doj": "28-05-2018",
"to_station": {
"lng": 78.0098161,
"lat": 27.1752554,
"code": "AGC",
"name": "AGRA CANTT"
},
"response_code": 200,
"boarding_point": {
"lng": 80.2755685,
"lat": 13.081674,
"code": "MAS",
"name": "CHENNAI CENTRAL"
},
"pnr": "4405474586",
"chart_prepared": false,
"journey_class": {
"code": "3A",
"name": null
},
THIS IS WHAT I HAVE TRIED USING VOLLEY
private void loaddata() {
String url = "https://api.railwayapi.com/v2/pnr-status/pnr/4655474586/apikey/q15rfl3kpz/";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
progressDialog.dismiss();
JSONObject obj = null;
try {
String str="";
obj = response.getJSONObject("name");
str = String.valueOf(obj);
TextView tv = (TextView)findViewById(R.id.textView);
tv.append(str);
}
}
}
}
}
JSONObject obj = (JSONObject) object;
String doj = (String) obj.get("doj")
You can use JSONObject obj to find out the value of key doj.
Latter on, if you want to have the doj as any other datatype you can parse in that. May be this could help. I don't have much idea on Volley :)

JAVA org.json not showing empty value

Here is my JAVA JSON code
#GET
#Consumes("application/x-www-form-urlencoded")
#Path("/getAllEmp")
public Response GetAllEmp() {
JSONObject returnJson = new JSONObject();
try {
ArrayList<Emp_Objects> objList = new ArrayList<Emp_Objects>();
DBConnection conn = new DBConnection();
objList = conn.GetEmpDetails();
JSONArray empArray = new JSONArray();
if (!objList.isEmpty()) {
GetLocation loc = new GetLocation();
for (Emp_Objects obj : objList) {
JSONObject jsonObj = new JSONObject();
jsonObj.put("id", obj.id);
jsonObj.put("name", obj.name);
jsonObj.put("email", obj.email);
jsonObj.put("address", obj.address);
empArray.put(jsonObj);
}
}
returnJson.put("data", empArray);
} catch (Exception e) {
}
return Response.ok(returnJson.toString()).header("Access-Control-Allow-Origin", "*").build();
}
When i execute this it gives me the following json
{
"data": [{
"id": 1,
"name": "123_name"
}, {
"id": 2,
"name": "321_name",
"email": "xyz#asd.com"
}]
}
In the above json email and address are missing because email and address is null on database.
So can i show json with empty value like following
{
"data": [{
"id": 1,
"name": "123_name",
"email": "",
"address": ""
}, {
"id": 2,
"name": "321_name",
"email": "",
"address": ""
}]
}
I am using JAVA and org.json with MySQL database.
If the objects are null, insert an empty String instead.
jsonObj.put("email", obj.email == null ? "" : obj.email);
jsonObj.put("address", obj.address == null ? "" : obj.address);
If you have a larger amount of rows to process, I recommend you to turn this is to a function for better readability and to save you some time.
jsonObj.put("email", nullToEmpty(obj.address));
private String nullToEmpty(String arg) {
return arg == null ? "" : arg;
}

Android : Json Parsing show error

[
{
"description": "My home",
"name": "Sweet Home",
"point": {
"lat": 22.890976,
"long": 90.459097
},
"type": 1,
"cid": "5319197376176516414"
}
This is my json file for parsing information. Here is my code for parsing name and lng.
BufferedReader jsonReader = new BufferedReader(new InputStreamReader(this.getResources().openRawResource(R.raw.map)));
StringBuilder jsonBuilder = new StringBuilder();
try {
for (String line = null; (line = jsonReader.readLine()) != null;) {
jsonBuilder.append(line).append("\n");
}
JSONTokener tokener = new JSONTokener(jsonBuilder.toString());
JSONArray jsonArray = new JSONArray(tokener);
JSONObject jsonObject = jsonArray.getJSONObject(0);
String title = jsonObject.getString("name");
String lhg = jsonObject.getJSONObject("point").getString("lng");
} catch (FileNotFoundException e) {
Log.e("jsonFile", "file not found");
} catch (IOException e) {
Log.e("jsonFile", "ioerror");
} catch (JSONException e) {
Log.e("jsonFile", "error while parsing json");
}
}
}
It show's me an exception error while parsing json. How do i solve that? What was my problem?
Because "Point" in your JSON object never contains a property called "lng"
String lhg = jsonObject.getJSONObject("point").getString("lng")
it does contain one named "long"
"point": {
"lat": 22.890976,
"long": 90.459097
},
So the code to fetch the longitude should look like this:
String lhg = jsonObject.getJSONObject("point").getString("long")
String lhg = jsonObject.getJSONObject("point").getString("lng") use "long" instead of lng.

Categories

Resources