Retrieving values from nested JSON using GSON - java

I'm working with JSON for the first time and my goal is to make an object with the properties Destination, Origin, and Duration from this JSON result (Google Distance Matrix API)
{
"destination_addresses" : [ "123 High St, Los Angeles, CA 90210, USA" ],
"origin_addresses" : [ "800 Lake Dr, Los Angeles, CA 90210, USA" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "2.0 km",
"value" : 1969
},
"duration" : {
"text" : "6 mins",
"value" : 338
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
So far I have been able to correctly store destination and origin using this line
Property data = new Gson().fromJson(json, Property.class);
But I am having a very hard time figuring out how to get the values from inside the nests. Specifically, I'm trying to grab the "text" from duration.
Any help would be greatly apprciated!

First create a container for the surrounding data.
class MainContent
{
public String destination_addresses;
public String bar;
public List<SubContent> subcontent;
}
Then you create a class for the nested data:
class SubContent
{
public String text;
}
The fields in either classes must have the same names as your json object does.
Then simply:
gson.fromJson(jsonData, MainContent.class);
GSON will attempt to reflect the values from the json string into the object.

Related

Combine Two Json Objects in java which is in single json array

I have one Json array which is consist 2 or 3 json objects, now I need to combine both the json objects into single json object, 1st json object is coming from one method 2nd is coming from another method let me explain with example
response[
{
"id" : 1,
"name" : "Hi",
"no.of slots" [
{
"Mrng" : 10:30,
"Evening" : 11:20
},
{
"Mrng" : 12:00,
"Evening" : 4:00
}
]
},
{
"email" : "abc#gmail.com",
"address" : "abc district"
"no.of slots" [
{
"Mrng" : 10:30,
"Evening" : 11:20
}
]
}
]
then I need output like
response: {
"id" : 1,
"name" : "Hi",
"no.of slots" [
{
"Mrng" : 10:30,
"Evening" : 11:20
},
{
"Mrng" : 12:00,
"Evening" : 4:00
}
],
"email" : "abc#gmail.com",
"address" : "abc district"
}
In no of slots If I have duplicates need to remove or if unique need to combine, any help will be appreciate.
Thanks in advance
You can have a class representing Mrng and Evening properties and override that class's equals and hash methods for comparing for these attributes. Then have a Set and generate instances and put elements to this.
Finally you will get a unique list and have a json string with some little research. This should be done to no.of.slots only

Use Variables in JSON and deserialize in POJO based on section

I have defined an example JSON below-
{ "common" : {
"data" : [ {
"ref" : "data1"
"x" : "${variable1}",
}, {
"ref" : "data2"
"y" : "${variable2}"
}
]
},
"section1" : {
"variables" : {
"${variable1}" : "var1_section1",
"${variable2}" : "var2_section1",
},
"data" : ["data1", "data2"]
},
"section2" : {
"variables" : {
"${variable1}" : "var1_section2"
"${variable2}" : "var2_section2",
},
"data" : ["data1", "data2"]
}
}
I have a common section and two more sections (section1 and section2). Data which is common for both sections is defined in the common section.
I have to deserialize this JSON into a POJO. Based on the section which will be passed as a parameter, the value of the variables should be deserialized for those sections. If I pass section1 as the parameter, the data should look like-
data : [ "x" : "var1_section1", "y" :"var2_section1" ]
And if I pass section2 as the parameter, the data should look like-
data : [ "x" : "var1_section2", "y" :"var2_section2" ]
I want to know if this is achievable using any JSON annotations in Java?

Get value out JSON Object containing JSON arrays

How can I get the value of "distance" out of the following JSON object with java?
{
"destination_addresses" : [ "New York City, New York, Verenigde Staten" ],
"origin_addresses" : [ "Washington D.C., District of Columbia, Verenigde Staten" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "225 mijl",
"value" : 361714
},
"duration" : {
"text" : "3 uur 51 min.",
"value" : 13877
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
I tried:
json.getJSONArray("rows").getJSONObject(0).getJSONObject("distance").toString();
But I always get org.json.JSONException: JSONObject["distance"] not found.
I think you are missing the second array "elements", you find array "row" so get object 0, in object 0 you need to find the "elements" array then take the object 0 again, so you can get the "distance" object.
Try this:
json.getJSONArray("rows").getJSONObject(0).getJSONArray("elements").getJSONObject(0).getJSONObject("distance").toString();
Again, I think. I hope this helped you.
Use java-json.jar
Convert JSON String to object and fetch the element.
You can refer this.
Try this:
package Sample;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class TestMain
{
public static void main(String[] args) throws JSONException
{
String s="{ \"destination_addresses\" : [ \"New York City, New York, Verenigde Staten\" ], \"origin_addresses\" : [ \"Washington D.C., District of Columbia, Verenigde Staten\" ], \"rows\" : [ { \"elements\" : [ { \"distance\" : { \"text\" : \"225 mijl\", \"value\" : 361714 }, \"duration\" : { \"text\" : \"3 uur 51 min.\", \"value\" : 13877 }, \"status\" : \"OK\" } ] } ], \"status\" : \"OK\"} ";
JSONObject jsonObj = new JSONObject(s);
JSONArray array= (JSONArray) jsonObj.get("rows");
JSONObject jsonObj2 =(JSONObject) array.get(0);
JSONArray array2= (JSONArray)jsonObj2.get("elements");
JSONObject jsonObj3 =(JSONObject) array2.get(0);
System.out.println(jsonObj3.get("distance"));
}
}
OUTPUT:
{"text":"225 mijl","value":361714}

How to decode this nested JSON string?

i tried many times to decode nested JSON string which consist of nested Array , i used GSON() to do that. and it's worked , but the problem is about objects inside this array don't be decoded from json, so i want your help :
JSON String :
{ "data" : { "current_condition" : [ { "cloudcover" : "75",
"humidity" : "87",
"observation_time" : "03:16 AM",
"precipMM" : "1.5",
"pressure" : "991",
"temp_C" : "11",
"temp_F" : "52",
"visibility" : "7",
"weatherCode" : "293",
"weatherDesc" : [ { "value" : "Patchy light rain" } ],
"weatherIconUrl" : [ { "value" : "http://cdn.worldweatheronline.net/images/wsymbols01_png_64/wsymbol_0033_cloudy_with_light_rain_night.png" } ],
"winddir16Point" : "SSW",
"winddirDegree" : "210",
"windspeedKmph" : "30",
"windspeedMiles" : "19"
} ],
"request" : [ { "query" : "London, United Kingdom",
"type" : "City"
} ],
"weather" : [ { "date" : "2014-01-03",
"precipMM" : "6.9",
"tempMaxC" : "10",
"tempMaxF" : "50",
"tempMinC" : "5",
"tempMinF" : "41",
"weatherCode" : "293",
"weatherDesc" : [ { "value" : "Patchy light rain" } ],
"weatherIconUrl" : [ { "value" : "http://cdn.worldweatheronline.net/images/wsymbols01_png_64/wsymbol_0017_cloudy_with_light_rain.png" } ],
"winddir16Point" : "SW",
"winddirDegree" : "220",
"winddirection" : "SW",
"windspeedKmph" : "33",
"windspeedMiles" : "21"
} ]
} }
my Code to decode this JSON :
HashMap HashMap = new Gson().fromJson(json, HashMap.class);
and it's output :
{data={request=[{query=London, United Kingdom, type=City}],
current_condition=[{cloudcover=75, humidity=87, observation_time=03:16
AM, precipMM=1.5, pressure=991, temp_C=11, temp_F=52, visibility=7,
weatherCode=293, weatherDesc=[{value=Patchy light rain}],
weatherIconUrl=[{value=http://cdn.worldweatheronline.net/images/wsymbols01_png_64/wsymbol_0033_cloudy_with_light_rain_night.png}],
winddir16Point=SSW, winddirDegree=210, windspeedKmph=30,
windspeedMiles=19}], weather=[{date=2014-01-03, precipMM=6.9,
tempMaxC=10, tempMaxF=50, tempMinC=5, tempMinF=41, weatherCode=293,
weatherDesc=[{value=Patchy light rain}],
weatherIconUrl=[{value=http://cdn.worldweatheronline.net/images/wsymbols01_png_64/wsymbol_0017_cloudy_with_light_rain.png}],
winddir16Point=SW, winddirDegree=220, winddirection=SW,
windspeedKmph=33, windspeedMiles=21}]}}
so i want an ideal method to give me ability to enter this nested HashMap array and it's values , because my method don't give me ability to call nested values from this array
Thank you ,
as the string represents a Hashmap inside another Hashmap you can use some thing like,
HashMap<String, HashMap> hashMap = new Gson().fromJson(json, HashMap.class);
It's worked after i did this method :
Type type = new TypeToken< HashMap<String, HashMap<String, ArrayList<com.google.gson.internal.LinkedTreeMap>>>>() {}.getType();
HashMap<String, HashMap<String, ArrayList<com.google.gson.internal.LinkedTreeMap>>> hashMap = new Gson().fromJson(API.getJSON(), type);
com.google.gson.internal.LinkedTreeMap hash = hashMap.get("data").get("current_condition").get(0);
System.out.println(" "+hash.get("humidity")+" ");
i know that your answers and my first method are true , but as i told you that i want to enter the entry nested array list inside this Json

google distance matrix api strange

I am facing a strange problem here,
when I run below url from web browser or from java command line
http://maps.googleapis.com/maps/api/distancematrix/json?origins=416%2063,Sweden&destinations=424%2069,Stor%C3%A5s%20Industrigatan%2020,Angered,G%C3%B6teborg&sensor=false
I get below results.
{
"destination_addresses" : [ "StorĂ¥s Industrigata 20, 424 69
Angered, Sweden" ],
"origin_addresses" : [ "Gothenburg, Sweden" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "10.4 km",
"value" : 10388
},
"duration" : {
"text" : "15 mins",
"value" : 924
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
but when I run the same url from glassfish server I mean sending an
http request from
form submit I get below strange response
{ "destination_addresses" : [ "" ],
"origin_addresses" : [ "Gothenburg, Sweden" ],
"rows" : [
{
"elements" : [
{
"status" : "NOT_FOUND"
}
]
}
],
"status" : "OK"
}
please not destination_addresses is empty in this case and status in
NOT_FOUND.
Java code I used to get the response is
private String getResponse(String URL) throws Exception {
InputStream stream = new URL(URL).openStream();
byte[] array = new byte[stream.available()];
stream.read(array);
return new String(array);
}
please guide me to resolve this issue,
thanks....
Use https
unless google will not let your software to connect.
and
get a api key.
read this:
https://developers.google.com/maps/documentation/distance-matrix/start
https://maps.googleapis.com/maps/api/distancematrix/json?origins=416%2063,Sweden&destinations=424%2069,Stor%C3%A5s%20Industrigatan%2020,Angered,G%C3%B6teborg&sensor=false&key=YOUR_API_KEY
be sure to replace YOUR_API_KEY with your actual API key
I had a similar problem when using the Distance Matrix API in Java. Setting the language in my request seems to make it work:
DistanceMatrixElement distanceMatrixElement;
DistanceMatrix matrix;
try
{
matrix = distanceMatrixApiRequest
.origins(...)
.destinations(...)
.language("en")
.await();
}

Categories

Resources