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));
}
Related
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.
I have a JSONArray from net.minidev.json which I want to convert to List<HashMap<String,Object>>.
There are many answers for converting the JSONArray using Gson.
However, I cannot add Gson as a dependency to my pom.xml, so I am looking for a way to achieve it with Java-8 features.
My JSONArray is something like this: It comprises multiple hierarchies.
[
{
"data": {
"name": "idris"
},
"children": [
{
"processStandardDeduction": 69394,
"cropId": 1,
"data": null,
"expectedQuantityPerAcre": 1220,
"name": "Red Tomato 1 quality",
"id": 1003,
"autoArchivePlotDays": 59902
},
{
"processStandardDeduction": 69394,
"cropId": 1,
"autoArchivePlotDays": 59902
},
{
"processStandardDeduction": 69394,
"cropId": 1,
"autoArchivePlotDays": 59902
}
],
"name": "Red Tomato",
"id": 1002
},
{
"data": null,
"name": "Red Tomato 1 quality",
"id": 1003,
"processStandardDeduction": 69394,
"cropId": 1,
"expectedQuantityPerAcre": 1220,
"cropName": "Tomato",
"autoArchivePlotDays": 59902
},
{
"data": null,
"name": "Red Tomato 3 quality",
"id": 1001,
"processStandardDeduction": 69394,
"autoArchivePlotDays": 59902
},
{
"processStandardDeduction": 69394,
"cropId": 1,
"data": null,
"id": 1004,
"autoArchivePlotDays": 59902
}
]
I would like to achieve same structure in List>
I tried looping each element of the JSONArray by converting it to each HashMap<String,Object> and then adding it to the List<HashMap<String,Object>>.
ObjectMapper mapper = new ObjectMapper();
List<HashMap<String, Object>> cropDetailsList = new ArrayList<>();
for (Object eachCropJson : cropDetails) { //cropDetails is the JSONArray
HashMap<String, Object> eachCropMap = (HashMap<String, Object>) mapper.convertValue(eachCropJson,
HashMap.class);
cropDetailsList.add(eachCropMap);
}
return cropDetailsList;
I would like to try a better approach using Java-8 features without using a forEach.
Thanks in advance.
If you get this JSON as String then you can use ObjectMapper.readValue method
readValue(String content, TypeReference valueTypeRef)
Code
List<HashMap<String, Object>> cropDetailsList = mapper.readValue(jsonString,
new TypeReference<List<HashMap<String, Object>>>(){});
In the same way if you want to iterate JSONArray
List<HashMap<String, Object>> cropDetailsList = cropDetails.stream()
.map(eachCropJson->(HashMap<String, Object>) mapper.convertValue(eachCropJson, HashMap.class))
.collect(Collectors.toList());
Using stream this can be done
List<HashMap<String, Object>> output = cropDetails.toList().stream().map(m -> ((HashMap<String, Object>) m)).collect(Collectors.toList());
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 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"));
}
}
I have this json:
[{
"name": "prog 1",
"show": [{
"name": "n1",
"time": "01.10 "
}, {
"name": "n2",
"time": "01.35 "
}]
}, {
"name": "prog 2",
"show": [{
"name": "n1",
"time": "01.10 "
}, {
"name": "n2",
"time": "01.35 "
}]
}]
Now trying to parse it in Java like:
JSONObject json=new JSONObject(json_str);
throws an Exception, since it doesn't begin with {, but [ since it's an array. I can parse this without problem in js, but aparently I cannot load an JSONArray with this string...
use: JSONArray objArray = new JSONArray (json_str);
// to access the individual objects inside the array:
for(int i=0;i<objArray.length();i++)
{
JSONObject obj = objArray.getJSONObject(i);
}
Have you tried this:
JSONArray arr = new JSONArray(stringWithContent);
Then access it like :
for(int i = 0; i<arr.length();i++){
System.out.println(arr.get(i));
}
You can try following code
JSONObject jObject = new JSONObject(json_str);
JSONArray array = jObject.getJSONArray("show");
for(int i = 0 ; i < array.length() ; i++)
{
System.out.println(array.getJSONObject(i).getString("name"));
System.out.println(array.getJSONObject(i).getString("time"));
}
It will helpful ...