I have a json response.I want to get the value of lat and lng from the json response.But i didn't get the values.Please Help me.Below is my response.
{
"html_attributions": [],
"results": [
{
"geometry": {
"location": {
"lat": 9.493837,
"lng": 76.338506
}
},
"icon": "http://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png",
"id": "2730a3d7ab068d666e61a02ce6160b4cd21a38c7",
"name": "Nagarjuna",
"place_id": "ChIJr0-U4vSECDsRtiALUlgZOzI",
"reference": "CmRcAAAA4yl72_x5llqvdshRJwuuntunXrYu33qdP5G7-I0CdHzcDsyd6wwqjxdNeqvT6vtRIoDoIk_WGNd62SYSoNEdBrpDrOcf5g5eZMj_vobhmF11mrujsQ_Yc7p-oGxQH0XtEhDNJdjQf_WlK_dRAckBzlA3GhQ_wzXs5RxoaxWDSEurm_R5syuovg",
"scope": "GOOGLE",
"types": [
"hospital",
"establishment"
],
"vicinity": "State Highway 40, Kodiveedu, Alappuzha"
},
{
"geometry": {
"location": {
"lat": 9.500542,
"lng": 76.341017
}
},
"icon": "http://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png",
"id": "d5b6c81a53a346dea1263de7a777703bc72b8796",
"name": "SYDNEY OPTICALS",
"opening_hours": {
"open_now": true,
"weekday_text": []
},
"photos": [
{
"height": 422,
"html_attributions": [],
"photo_reference": "CnRnAAAA_jg-NlSrVKkDOP7wXhPhvFTD8NW4A4aDI_Ptl3F9c_qt9QwdztNTG9Cr51uGIphpEUMyhsTfhhaa-TlfoL8MUEffbguZJ1AhKUwzfe7Mbrvm2KW8Y1EQXVw_3FglxA4LM1hqWJCK_AV4xcvOw1vuHRIQ8_keBYr29H8jK145RQ_PkRoUgPZ0qzcSNdIntc2ZI4WvBIR-TBQ",
"width": 630
}
],
"place_id": "ChIJl9tvIV6ECDsR7Cmf3KkIl-4",
"reference": "CnRjAAAA3qhFUcb8P9akE8xw-KwfF6OU6qvy2cVX4Sg0qK_xCOfeUEyxoFgwof8rk-Z2BBJ7Z4m7ZTbfdp78wqFbeLfojQWPldq7XDfzX0pLScBSysebEp9P4XmrsAO5qyqSUveb5jWcJDkYiOLKgaKMzoWQphIQbldrdJ9iEDHkGiQ7tleNYxoUnjcjcynUDMftaErRUQbOn-GkWj0",
"scope": "GOOGLE",
"types": [
"store",
"hospital",
"health",
"establishment"
],
"vicinity": "Mullakkal, Alappuzha"
}
],
"status": "OK"
}
This is the google api response i used for getting the list of hospitals.Anybode plese help me.Thanks in advance.
Use these steps:
Create a model class for that Json Response
Use Gson to parse the response
Then create an object of the class
using the object get the data variable from the class
I hope I can help.
First, validate your JSON with http://jsonlint.com/
Second, use this site to generate POJO: http://www.jsonschema2pojo.org/
make sure that Annotation GSON and Source type JSON are clicked ON!
Copy your classes in to your project.
Third: use GSON in Android :) (Retrofit is good for this)
Supposing you use the json.org Implementation for Java:
String response = "{\"html_attributions\": [], \"results\": ...";
JSONObject jo = new JSONObject(response);
JSONObject result = jo.getJSONArray("results").getJSONObject(0);
JSONObject location = result.getJSONObject("geometry").getJSONObject("location");
double lat = location.getDouble("lat");
double lng = location.getDouble("lng");
try this
String response = "{\"html_attributions\": [], \"results\": ...";
JSONObject objResponce = new JSONObject(response);
JSONArray arrayResults=new JSONArray(objResponce.getString("results"));
if(arrayResults.length()>0)
{
for(int i=0;i<arrayResults.length();i++)
{
//--- get each json object from array -----
JSONObject objArrayResults = arrayResults.getJSONObject(i);
//--- get geometry json object from each object of array -----
JSONObject objGeometry=new JSONObject(objArrayResults.getString("geometry"));
//--- get location json object from geometry json object -----
JSONObject objLocation=new JSONObject(objGeometry.getString("location"));
System.out.println("Latitude :"+objLocation.getString("lat"));
System.out.println("Longitude :"+objLocation.getString("lng"));
}
}
Related
I am obtaining a JSON response from an API that gives me a list of call records formatted as JSON. I want to parse through the data and find the record ID, my trouble is that each JSON record has multiple ID's and I am not sure how to access the correct one. Keep in mind, I do not know the value of the ID is "3461487000073355176" prior to running the request.
This is my code to receive the JSON, I created a JSONObject so I can hopefully store the value.
1.
Response response = client.newCall(request).execute();
String responseBody = response.body().string();
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser parser = new JsonParser();
JsonElement je = parser.parse(responseBody);
String prettyJsonString = gson.toJson(je);
JSONObject json = new JSONObject(prettyJsonString);
System.out.println("Json = " + json);
The JSON the ID I need to access has a comment next to it:
"data": [
{
"Owner": {
"name": "My namen",
"id": "346148700000017",
"email": "m#gmail.com"
},
"$state": "save",
"$process_flow": false,
"Street": "95## ### ######",
"id": "**3461487000073355176**", ----This is the ID I need -----
"Coverage_A_Dwelling": 100000,
"$approval": {
"delegate": false,
"approve": false,
"reject": false,
"resubmit": false
},
"Created_Time": "2020-12-10T09:05:17-05:00",
"Property_Details": "Primary Residence",
"Created_By": {
"name": "My name",
"id": "346148700000017",
"email": "m#gmail.com"
},
"Description": "Created on Jangl: https://jan.gl/crwp773ytg8",
"$review_process": {
"approve": false,
"reject": false,
"resubmit": false
},
"Property_State": "FL",
"Property_Street": "95",
"Roof_Material": "Asphalt Shingle",
"Full_Name": "Clare Em",
"Property_City": "Land ",
"Email_Opt_Out": false,
"Lead_I_D": "4FFEC0C5-FBA1-2463-DB9B-C38",
"Insured_1_DOB": "1942-02-20",
"$orchestration": false,
"Tag": [],
"Email": "cr#yahoo.com",
"$currency_symbol": "$",
"$converted": false,
"Zip_Code": "338",
"$approved": true,
"$editable": true,
"City": "Land O Lakes",
"State": "FL",
"Structure_Type": "Single Family",
"Prior_Carrier": {
"name": "Default Carrier (DO NOT DELETE OR CHANGE)",
"id": "3461487000000235093"
},
"Source": {
"name": "EverQ",
"id": "346148700006474"
},
"First_Name": "Clarence",
"Modified_By": {
"name": "My name",
"id": "3461487000000172021",
"email": "m#gmail.com"
},
"Phone": "7036159075",
"Modified_Time": "2020-12-10T09:05:17-05:00",
"$converted_detail": {},
"Last_Name": "####",
"$in_merge": false,
"$approval_state": "approved",
"Property_Zip": "34638"
}
],
"info": {
"per_page": 200,
"count": 1,
"page": 1,
"more_records": false
}
}
If I understood it correctly, you can get the id like this:
Here, json has the following value.
[
{
"Owner": {
"name": "My namen",
"id": "346148700000017",
"email": "m#gmail.com"
},
"id": "**3461487000073355176**"
...
}
]
Now I can iterate over JSONArray to get the id.
JSONArray jsonArray = new JSONArray(json);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = (JSONObject) jsonArray.get(i);
String id = (String) jsonObject.get("id");
System.out.println(id);
}
It prints out **3461487000073355176**.
You can do jsonObject.getJSONArray("data"); in your example to obtain JSON array.
The posted JSON response is missing the initial "{".
Your JSON contains data, which is a JSONArray of Owner objects. To get the id field of the first owner (array element 0):
// existing code
JSONObject json = new JSONObject(prettyJsonString);
System.out.println("Json = " + json);
// get the id field
JSONArray dataArray = (JSONArray)json.get("data");
JSONObject data0 = (JSONObject) dataArray.get(0);
JSONObject owner = (JSONObject) data0.get("Owner");
String id = owner.getString("id");
System.out.println(id);
Not sure if understood correctly but if you need to get all the IDs in that "level" why don't you try to model it as a class instead of using parser and let Gson do the parsing (this class might be useful later if you need to add more details)?
For example, defining something like this:
#Getter #Setter
// This models the response string from body
public class Response {
#Getter #Setter
// This models objects in the data list/array
public static class IdHolder {
// Only id because not interested of the rest
private String id;
}
// Only list of id holders because not interested of the rest
private List<IdHolder> data;
}
Then it would be as easy as:
Response res = gson.fromJson(responseBody, Response.class);
// Print out what you got
res.getData().stream().map(IdHolder::getId).forEach(System.out::println);
My Json FILE (it´s an array! )
[
{
"datasetid": "country-flags",
"recordid": "d661d0a8676bf4d7563114c1d9c465987df22132",
"fields": {
"num_un": 32,
"geolocation": [
-38.416097,
-63.616672
],
"dialing_code": "54",
"a3_un": "ARG",
"country": "Argentina",
"flag": {
"mimetype": "image/png",
"format": "PNG",
"filename": "ar.png",
"width": 16,
"id": "fceb4235ce95c8597bfa77d0db0181a0",
"height": 11,
"thumbnail": true
},
"a2_iso": "AR"
},
"geometry": {
"type": "Point",
"coordinates": [
-63.616672,
-38.416097
]
},
"record_timestamp": "2016-09-26T07:48:38.162+02:00"
},
more...
]
So i want to get the value from coordinates. So for this i tried to work with this:
JsonReader jsonReader = Json
.createReader(new FileReader(getClass().getResource("country-flags.json").getPath()));
JsonArray arr = jsonReader.readArray();
for(int i = 1; i<arr.size();i++)
{
JsonObject obj = arr.getJsonObject(i);
System.out.println("coordinates: " + obj.containsKey("\"coordinates\""));
System.out.println("##########");
System.out.println(obj.getValue("\"coordinates\""));
}
But i got the error:
javax.json.JsonException: A non-empty JSON Pointer must begin with a
'/'
Can someone help me out ?!
Your code obj.containsKey("\"coordinates\"") will return false as coordinates is NOT a top level key, but is a 2nd level (nested) key. If you print obj.keySet(), you will get [datasetid, recordid, fields, geometry, record_timestamp] (first / top level keys only).
If the structure of your JSON is fixed, you can use the following code:
for(int i = 1; i<arr.size();i++)
{
JsonObject obj = arr.getJsonObject(i);
JsonObject jsonChildObject = obj.getJsonObject("geometry");
if(jsonChildObject.containsKey("coordinates"))
System.out.println(jsonChildObject.getValue("/coordinates"));
}
Notice the / in front of the getValue method's coordinates param. I think that was the reason you were here in the first place.
This is my JSON,
{
"city": {
"id": 2961297,
"name": "Swords",
"coord": {
"lon": -6.21806,
"lat": 53.459721
},
"country": "IE",
"population": 0
},
"cod": "200",
"message": 0.3535,
"cnt": 1,
"list": [
{
"dt": 1481025600,
"temp": {
"day": 284.68,
"min": 284.68,
"max": 285.36,
"night": 285.36,
"eve": 284.8,
"morn": 284.68
},
"pressure": 1028.26,
"humidity": 95,
"weather": [
{
"id": 500,
"main": "Rain",
"description": "light rain",
"icon": "10d"
}
],
"speed": 9.01,
"deg": 186,
"clouds": 92,
"rain": 0.5
}
]
}
I am trying to access the rain value "rain": 0.5 as seen in the returned JSON data above I am unsure how exactly to do this as I don't have much experience working with JSON data.
This is my code,
JSONObject topLevel = new JSONObject(builder.toString());
JSONArray ListArray = topLevel.getJSONArray("list");
weather = String.valueOf(ListArray);
for(int x = 0;x < ListArray.length();x++) {
JSONObject myObj = ListArray.getJSONObject(x);
myObj.getInt("rain");
Log.d("TODAYS Rain"+rain,"");
//System.out.Print("Current Weather" +id+main+icon+dscription+rain);
}
Any help is greatly appreciated.
JSONObject topLevel = new JSONObject(builder.toString());
JSONArray listArray = topLevel.getJSONArray("list");
JSONObject firstObject = (JSONObject)listArray.get(0);
Double rain = firstObject.getDouble("rain");
System.out.println("TODAYs rain :" + rain);
}
The easiest way is to parse a Json is to use POJO classes that map the Json into an object instance.
You define the class structure and it gets filled with the data retrieved.
There is a guide on that same topic on this website: http://www.ssaurel.com/blog/learn-how-to-parse-json-in-android-with-gson/
JSONObject topLevel = new JSONObject(builder.toString());
JSONArray ListArray = topLevel.getJSONArray("list");
weather = String.valueOf(ListArray);
for(int x = 0;x < ListArray.length();x++) {
JSONObject myObj = ListArray.getJSONObject(x);
myObj.getDouble("rain");
Log.d("TODAYS Rain"+rain,"");
//System.out.Print("Current Weather" +id+main+icon+dscription+rain);
}
You just need to use myobj.getDouble("rain") instead of myobj.getInt("rain") as the value of rain is not integer.
I have this JSON I need to parse. Its format looks something likes this:
{
"47M": [
{
"lat": 39.95507,
"lng": -75.152122,
"label": 8011,
"VehicleID": 8011,
"BlockID": 7995,
"Direction": "NorthBound",
"destination": "Spring Garden via 9th St.",
"Offset": 1,
"Offset_sec": 29
},
{
"lat": 39.913765,
"lng": -75.155464,
"label": 8038,
"VehicleID": 8038,
"BlockID": 7993,
"Direction": "NorthBound",
"destination": "Spring Garden via 9th St.",
"Offset": 3,
"Offset_sec": 158
}
]
}
However, that "47M" can be "5", "H", "101", etc. And I need to get those "5", "H", etc.
I believe I should use the loop for (obj : root) , but I don't know what's the type for obj
You could use simple json (https://code.google.com/p/json-simple/) Library and code like this to iterate over the keys.
JSONParser parser = new JSONParser();
jObject = parser.parse(jsonString);
JSONObject jsonObject = (JSONObject) jObject;
for(Iterator iterator = jsonObject.keySet().iterator(); iterator.hasNext();) {
String key = (String) iterator.next();
System.out.println(jsonObject.get(key));
}
I have this response that I get back form server. I want to parse it and get the hospital_name out of it. How would I go about it?
[
{
"Hospital": {
"id": "63083",
"hospital_name": "Colorado Mental Health Inst",
"hospital_add_1": "1600 W 24th St",
"hospital_add_2": null,
"hospital_city": "Pueblo",
"hospital_state": "CO",
"hospital_zip": "81003",
"hospital_phone": "719-546-4000\r",
"hospital_fax": null,
"hospital_description": null,
"callcenter_agent_approval": "0",
"hospital_site": "",
"mdpocket_approval": "0",
"facebook": ""
},
"Floor": [],
"Department": [],
"Image": [],
"Notes": []
},
{
"Hospital": {
"id": "63084",
"hospital_name": "Parkview Medical Center",
"hospital_add_1": "400 W 16th St",
"hospital_add_2": null,
"hospital_city": "Pueblo",
"hospital_state": "CO",
"hospital_zip": "81003",
"hospital_phone": "719-584-4000\r",
"hospital_fax": null,
"hospital_description": null,
"callcenter_agent_approval": "0",
"hospital_site": "",
"mdpocket_approval": "0",
"facebook": ""
},
"Floor": [],
"Department": [],
"Image": [],
"Notes": []
},
{
"Hospital": {
"id": "63085",
"hospital_name": "St Mary-Corwin Medical Center",
"hospital_add_1": "1008 Minnequa Ave",
"hospital_add_2": null,
"hospital_city": "Pueblo",
"hospital_state": "CO",
"hospital_zip": "81004",
"hospital_phone": "719-560-4000\r",
"hospital_fax": null,
"hospital_description": null,
"callcenter_agent_approval": "0",
"hospital_site": "",
"mdpocket_approval": "0",
"facebook": ""
},
"Floor": [],
"Department": [],
"Image": [],
"Notes": []
}
]
EDITED THE JSON
*UPDATED JSON *
[ // json array node
{ // json object node
"Hospital": { // json object Hospital
To parse
JSONArray jr = new JSONArray("jsonstring");
for(int i=0;i<jr.length();i++)
{
JSONObject jb = (JSONObject)jr.getJSONObject(i);
JSONObject jb1 =(JSONObject) jb.getJSONObject("Hospital");
String name = jb1.getString("hospital_name");
Log.i("name....",name);
}
Log
02-18 03:09:43.950: I/name....(951): Colorado Mental Health Inst
02-18 03:09:43.950: I/name....(951): Parkview Medical Center
02-18 03:09:43.950: I/name....(951): St Mary-Corwin Medical Center
You won't- its invalid JSON. You're missing most of your "" around field names.
Try this..
JSONArray tot_array = new JSONArray(response);
for(int i = 0; i< tot_array.length(); i++){
JSONObject obj = tot_array.getJSONObject(i);
JSONObject hospital_obj = obj.getJSONObject("Hospital");
String hospital_name = hospital_obj.getString("hospital_name");
}
I recommend you use the fastjson (https://github.com/alibaba/fastjson).
Checkout this cool libray for parsing JSOn in Android its called GSON https://code.google.com/p/google-gson/ . Via this parsing this very simple.
Your string is not a valid JSON object. Check out jsonlint before trying to parse a string as JSON. After which, you can read about parsing JSON in Android. It's easy enough with the built-in org.json, but should be much easier if you use one of the many Java libraries out there that simplifies it further. You can look into Jackson or google-gson, two of the most capable utilities for your purpose.