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
Related
I have an String called inputJson that contains
{"listPruebas": [
{
"nombrePrueba" : "pruebaA",
"id" : 1,
"tipoPrueba" : "PRUEBABASE1",
"elementoBase" : "tipoA",
"listaMarca": [
{
"elemento": "elemento1 ",
"tipo": "ABC",
"cadena": "SFSG34235WF32"
},
{
"elemento":"elemento2",
"tipo":"DEF",
"cadena":"DJRT64353GSDG"
},
{
"elemento" : "elemento3",
"formato ":"JPG"
}
]},
{
"nombrePrueba" : "pruebaB",
"id" : 2,
"tipoPrueba" : "PRUEBABASE2",
"elementoBase" : "imagenPrueba",
"listaMarca2": [
{
"elemento" : "imagen",
"tipo": "tipo5",
"cadena": "iVBORw0KGgoAAAANSUhEUgAAAgAAAA"
}
]
}
],
"listaBuscar":
[
{
"tipoBusqueda":"busqueda1",
"id" : 1,
"operacion" : "operacion1",
"valor" : "12"
},
{
"tipoBusqueda":"binario",
"id" : 2,
"operacion" : "operacion2",
"valor" : "13"
},
{
"tipoFiltro":"numerico",
"id" : 31,
"operacion" : "MENOR_QUE",
"valor" : "1980",
"intervalo" : 1
}
]
}
and I converted the String to JSONObject of this way
JSONObject object = new JSONObject(inputJson);
and I got this
jsonObject::{"listaBuscar":[{"valor":"12","id":1,"operacion":"operacion1","tipoBusqueda":"busqueda1"},{"valor":"13","id":2,"operacion":"operacion2","tipoBusqueda":"binario"},{"tipoFiltro":"numerico","intervalo":1,"valor":"1980","id":31,"operacion":"MENOR_QUE"}],"listPruebas":[{"listaMarca":[{"tipo":"ABC","elemento":"elemento1","cadena":"SFSG34235WF32"},{"tipo":"DEF","elemento":"elemento2","cadena":"DJRT64353GSDG"},{"elemento":"elemento3","formato":"JPG"}],"elementoBase":"tipoA","tipoPrueba":"PRUEBABASE1","nombrePrueba":"pruebaA","id":1},{"elementoBase":"imagenPrueba","tipoPrueba":"PRUEBABASE2","listaMarca2":[{"tipo":"tipo5","elemento":"imagen","cadena":"iVBORw0KGgoAAAANSUhEUgAAAgAAAA"}],"nombrePrueba":"pruebaB","id":2}]}
and now I need to extract information but I dont know how to do, for example I try this
object.getString("elemento1");
but I got this error
Caused by: org.json.JONException: JSONObject["elemento1"] not found
help me please
You can't get a nest JSON object from the top level. It's like a treemap. You need to convert it into a java object or get it level by level.
check this post, a lot of ways.
You json contains two json arrays, fetch them as -
JSONArray listaBuscArray = jsonObj.getJSONArray("listaBuscar");
JSONArray listPruebasArray = jsonObj.getJSONArray("listPruebas");
Now you can process and use them as -
for(int i=0; i<listaBuscArray.length; i++){
JSONObject obj = listaBuscArray.getJSONObject(i);
.... your logic
}
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}
I'm getting an JSON array as a string value and I need to create a JSON object using that. array code is like this.
{"eventsList" : [
"requestId" : "82334-adf86d-8bac8ef-289c"
events:[
{
"eventType" : "receiveLocation_Event",
"externalId" : "973af2f8-820b-457b-89c2",
"description" : "Test Event",
"whenOccurred" : "06-Aug-2013 07.15.01.0 AM",
"partnerId" : "cecdbd94-ac60-4db0-b7f2",
"tagsAndValues" : {
"locationAccuracy" : "10",
"attr2" : "value2"
},
"count" : "2"
},
{
"eventType" : "SEND_SMS_sendSmsEvent",
"externalId" : "45af4f8-87-4f42b-832abc",
"description" : "Another Test Event",
"whenOccurred" : "06-Aug-2013 08.16.01.0 AM",
"partnerId" : "cecdbd94-ac60-4db0-b7f2",
"tagsAndValues" : {
"messageLength" : "135",
"attrX" : "valueX"
},
"count" : "1"
}
]
}
]
}
i try to create an JSON object using folowing code line
SONObject jsonObject = new JSONObject(string);
I'm getting an error when i run this.
org.json.JSONException: Expected a ',' or ']' at character 35
at org.json.JSONTokener.syntaxError(JSONTokener.java:413)
at org.json.JSONArray.<init>(JSONArray.java:143)
at org.json.JSONTokener.nextValue(JSONTokener.java:351)
at org.json.JSONObject.<init>(JSONObject.java:206)
at org.json.JSONObject.<init>(JSONObject.java:420)
Please help me to solve this issue.
There are several mistakes.
After [ a list of comma-separated values is expected, but you have a colon after "requestId". You probably meant for the [ on line 1 to be a {.
Given the last issue, you probably want a comma after "82334-adf86d-8bac8ef-289c"
If you drop your text into an online JSON formatter and validator, such as this one it will point out all your errors.
Problem is here:
...
"requestId" : "82334-adf86d-8bac8ef-289c"
events:...
You forgot some punctuation:
...
"requestId" : "82334-adf86d-8bac8ef-289c",
"events":......
Use this instead this is JSON syntax. All keys are strings.
This is how the String should be;
{"eventsList" : [
{"requestId" : "82334-adf86d-8bac8ef-289c"},
{ "events":[
{
"eventType" : "receiveLocation_Event",
"externalId" : "973af2f8-820b-457b-89c2",
"description" : "Test Event",
"whenOccurred" : "06-Aug-2013 07.15.01.0 AM",
"partnerId" : "cecdbd94-ac60-4db0-b7f2",
"tagsAndValues" : {
"locationAccuracy" : "10",
"attr2" : "value2"
},
"count" : "2"
},
{
"eventType" : "SEND_SMS_sendSmsEvent",
"externalId" : "45af4f8-87-4f42b-832abc",
"description" : "Another Test Event",
"whenOccurred" : "06-Aug-2013 08.16.01.0 AM",
"partnerId" : "cecdbd94-ac60-4db0-b7f2",
"tagsAndValues" : {
"messageLength" : "135",
"attrX" : "valueX"
},
"count" : "1"
}
]
}
]
}
the requestId and event must be like this: {"requestId" : "82334-adf86d-8bac8ef-289c"},
{ "events":
And also there must be closing } after closing the inner JSONArray ]
How can I navigate JSON string from one key to another nested key and get the value? I have the following string
{ "data" : { "current_condition" : [ { "cloudcover" : "75",
"humidity" : "29",
"observation_time" : "07:59 PM",
"precipMM" : "0.0",
"pressure" : "1011",
"temp_C" : "19",
"temp_F" : "67",
"visibility" : "16",
"weatherCode" : "116",
"weatherDesc" : [ { "value" : "Partly Cloudy" } ],
"weatherIconUrl" : [ { "value" : "http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0002_sunny_intervals.png" } ],
"winddir16Point" : "N",
"winddirDegree" : "350",
"windspeedKmph" : "26",
"windspeedMiles" : "16"
} ],
"request" : [ { "query" : "01801",
"type" : "Zipcode"
} ],
"weather" : [ { "date" : "2011-05-09",
"precipMM" : "0.0",
"tempMaxC" : "19",
"tempMaxF" : "65",
"tempMinC" : "10",
"tempMinF" : "50",
"weatherCode" : "113",
"weatherDesc" : [ { "value" : "Sunny" } ],
"weatherIconUrl" : [ { "value" : "http://www/images/wsymbols01_png_64/wsymbol_0001_sunny.png" } ],
"winddir16Point" : "NNW",
"winddirDegree" : "348",
"winddirection" : "NNW",
"windspeedKmph" : "24",
"windspeedMiles" : "15"
},
{ "date" : "2011-05-10",
"precipMM" : "0.1",
"tempMaxC" : "13",
"tempMaxF" : "56",
"tempMinC" : "12",
"tempMinF" : "53",
"weatherCode" : "122",
"weatherDesc" : [ { "value" : "Overcast" } ],
"weatherIconUrl" : [ { "value" : "http://www/images/wsymbols01_png_64/wsymbol_0004_black_low_cloud.png" } ],
"winddir16Point" : "NNE",
"winddirDegree" : "12",
"winddirection" : "NNE",
"windspeedKmph" : "31",
"windspeedMiles" : "19"
}
]
} }
So I answer my own question:
In case someone else want to get value quickly: This is what I was looking for.
JSONObject j = new JSONObject(strResponse);
String weatherDesc = jObject.getJSONObject("data").getJSONArray("weather").getJSONObject(0).getJSONArray("weatherDesc").getJSONObject(0).getString("value");
There are JSON libraries in pretty much any language. If you suggest one, I might be able to point you to something.
In the meantime, here are a few:
Perl JSON library
Python's is built in
Javascript serializes its objects in JSON so it's super easy
C# library -- also see C# - parsing json formatted data into nested hashtables
Here's the Android JSON reference
And so on. I suggest a quick google for the language of your choice.
Generally speaking you will use a library that is already built specifically for you language, what language are you trying to read the data in? Many languages have a couple of libraries available, some languages may have built in support, like JavaScript.
if you just need to understand the data, it is pretty readable...
I am passing a map to a Json body of POST request, but not getting proper format.
Below is my code:
Map<String,Double> Last12MSalesTransaction_c = new Map<String,Double>();
Last12MSalesTransaction_c.put('1',l.Booking_Details_in_rupees_1M__c);
Last12MSalesTransaction_c.put('2',l.Booking_Details_in_rupees_2M__c);
Last12MSalesTransaction_c.put('3',l.Booking_Details_in_rupees_3M__c);
Last12MSalesTransaction_c.put('4',l.Booking_Details_in_rupees_4M__c);
Last12MSalesTransaction_c.put('5',l.Booking_Details_in_rupees_5M__c);
Last12MSalesTransaction_c.put('6',l.Booking_Details_in_rupees_6M__c);
string jsonstring = JSON.serialize(Last12MSalesTransaction_c);
String body='{'+
'"LeadSource":"'+ls.name+'",'+
'"LoanAmount":'+l.Amount_in_Rs__c+','+
'"Off_Stability":'+l.Office_Stability_in_Months__c+','+
'"Opportunity_Record_Type":"'+l.Business_Type__c+'",'+
'"PAN_ID":"'+l.PAN__c+'",'+
'"Program_Type":"'+l.Program_Type__c+'",'+
'"P1":'+l.Purchase_Price__c+','+
'"Last12MSalesTransaction":"'+jsonstring+'"'+
'}';
And here is the json which is generated:
Body{"LeadSource":"UltraCash","LoanAmount":0,"Off_Stability":0,"Opportunity_Record_Type":"Consumer Loan","PAN_ID":"AOJPM2131F","Program_Type":"null","P1":0,"Last12MSalesTransaction":"{"12":21.0,"11":20.0,"10":19.0,"9":18.0,"8":17.0,"7":16.0,"6":15.0,"5":14.0,"4":13.0,"3":12.0,"2":11.0,"1":10.0}"}
But I want json in below format:
{
"LeadSource": "UltraCash",
"LoanAmount": 0,
"Off_Stability": 0,
"Opportunity_Record_Type": "Consumer Loan",
"PAN_ID": "AOJPM2131F",
"Program_Type": "null",
"P1": 0,
"Last12MSalesTransaction": [
{
"key" : "1", "value" : 10
},
{
"key" : "2", "value" : 15
},
{
"key" : "3", "value" : 10
},
{
"key" : "4", "value" : 10
},
{
"key" : "5", "value" : 20
},
{
"key" : "6", "value" : 30
}
]
}
Please suggest me a way to get expected result.
List<javafx.util.Pair<String, Double>> Last12MSalesTransaction = newArrayList(
new javafx.util.Pair("1", 10),
new javafx.util.Pair("2", 15),
new javafx.util.Pair("3", 10)
);
Result:
[ {
"key" : "1",
"value" : 10
}, {
"key" : "2",
"value" : 15
}, {
"key" : "3",
"value" : 10
} ]