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...
Related
I want to update request fields only in an array using java.This is my existing document in mongo db:
{
"_id": "6691e5068dwe335w42cb0a699650f",
"Opportunity_Owner": "Self",
"Account_Name": "IC",
"Lead_Source": "Callbox",
"Opportunity_Name": "name1 ",
"Stage": "Proposal",
"Stage_Status": "A",
"1555570551211": [],
"1555556165153": [],
"1555556059584": [{
"id": "1557389940585",
"Notes": "Note 1"
},
{
"id": "1557389945398",
"Notes": "Hi Bobby "
},
{
"id": "1557389978181",
"Notes": "Spoken to Bobby."
},
{
"id": "1557389990159",
"Notes": "plan to call on 29/Apr"
}
],
"createdBy": "2c18b8dbb7d74a41a66f53a90117480a",
"createdDate": "1562911250917"
}
Request payload:
{
"_id" : "6691e5068dwe335w42cb0a699650f",
"Stage_Status" : "I",
"1555556059584" : [
{
"id" : "1557389940585",
"Notes" : "updated note 123"
}
]
}
I am trying to update "Stage_Status" and "1555556059584.Notes" at a time using $set.I am able to update "Stage_Status" but "1555556059584" array is going to reset with what i have updated with last one.
expected output:
{
"_id" : "6691e5068dwe335w42cb0a699650f",
"Opportunity_Owner" : "Self",
"Account_Name" : "IC",
"Lead_Source" : "Callbox",
"Opportunity_Name" : "name1 ",
"Stage" : "Proposal",
"Stage_Status" : "I",
"1555570551211" : [],
"1555556165153" : [],
"1555556059584" : [
{
"id" : "1557389940585",
"Notes" : "updated note 123"
},
{
"id" : "1557389945398",
"Notes" : "Hi Bobby "
},
{
"id" : "1557389978181",
"Notes" : "Spoken to Bobby."
},
{
"id" : "1557389990159",
"Notes" : "plan to call on 29/Apr"
}
],
"createdBy" : "2c18b8dbb7d74a41a66f53a90117480a",
"createdDate" : "1562911250917"
}
can any one please help me to figure it out in java.
I guess you wanted to update Stage_Status and 1555556059584.Notes at Once .
here is a demo about it
> db.student.find()
{ "_id" : ObjectId("5d2c09ea8ed60ae70d3dd76b"), "name" : "bigbang", "courses" : [ { "name" : "en", "classRoom" : "9001" }, { "name" : "math", "classRoom" : "1001" } ] }
> db.student.update({name:'bigbang','courses.name':'en'},{ $set: {'courses.$.classRoom':'1009',name :"course"} })
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.student.find()
{ "_id" : ObjectId("5d2c09ea8ed60ae70d3dd76b"), "name" : "course", "courses" : [ { "name" : "en", "classRoom" : "1009" }, { "name" : "math", "classRoom" : "1001" } ] }
the java demo is like this
collection.updateOne(and(eq("Stage_Status","A"),eq("1555556059584.id","1557389940585")),new Document("$set" ,new Document("Stage_Status","YOUR_NEW_VALUE").append("1555556059584.$.Notes","YOUR_NEW_VALUE")));
you must set the 1555556059584.id to let the diver know which element to be update .
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 ]
Ok so I am making API requests to retrieve certain things like movies, songs, or to ping the server. However all of these responses are contained within the same response JSON object that has varying fields depending on the response. Below are three examples.
ping
{
"response" : {
"status" : "ok",
"version" : "0.9.1"
}
}
getIndexes
{
"response" : {
"status" : "ok",
"version" : "0.9.1",
"indexes" : {
"index" : [ {
"name" : "A",
"movie" : [ {
"id" : "150",
"name" : "A Movie"
}, {
"id" : "2400",
"name" : "Another Movie"
} ]
}, {
"name" : "S",
"movie" : [ {
"id" : "439",
"name" : "Some Movie"
}, {
"id" : "209",
"name" : "Some Movie Part 2"
} ]
} ]
}
}
}
getRandomSongs
{
"response" : {
"status" : "ok"
"version" : "0.9.1"
"randomSongs" : {
"song": [ {
"id" : "72",
"parent" : "58",
"isDir" : false,
"title" : "Letter From Yokosuka",
"album" : "Metaphorical Music",
"artist" : "Nujabes",
"track" : 7,
"year" : 2003,
"genre" : "Hip-Hop",
"coverArt" : "58",
"size" : 20407325,
"contentType" : "audio/flac",
"suffix" : "flac",
"transcodedContentType" : "audio/mpeg",
"transcodedSuffix" : "mp3",
"duration" : 190,
"bitRate" : 858,
"path" : "Nujabes/Metaphorical Music/07 - Letter From Yokosuka.flac",
"isVideo" : false,
"created" : "2015-06-06T01:18:05.000Z",
"albumId" : "2",
"artistId" : "0",
"type" : "music"
}, {
"id" : "3135",
"parent" : "3109",
"isDir" : false,
"title" : "Forty One Mosquitoes Flying In Formation",
"album" : "Tame Impala",
"artist" : "Tame Impala",
"track" : 4,
"year" : 2008,
"genre" : "Rock",
"coverArt" : "3109",
"size" : 10359844,
"contentType" : "audio/mpeg",
"suffix" : "mp3",
"duration" : 258,
"bitRate" : 320,
"path" : "Tame Impala/Tame Impala/04 - Forty One Mosquitoes Flying In Formation.mp3",
"isVideo" : false,
"created" : "2015-06-29T21:50:16.000Z",
"albumId" : "101",
"artistId" : "30",
"type" : "music"
} ]
}
}
}
So basically my question is, how should I structure my model classes to use for parsing these responses? At the moment I have an abstract response object that only contains fields for the status and version. However, by using this approach I will need a response class that extends this abstract class for ever request I make (e.g. AbstractResponse, IndexesResponse, RandomSongsResponse). Also, some models with the same name may have different fields depending on the API request made. I would prefer to avoid making a model class for every possible scenario.
And as an extra note, I am using GSON for JSON serialization/deserialization and Retrofit to communicate with the API.
I'm aware of the writerWithDefaultPrettyPrinter option in Jackson, but is there any way to customize it? See examples below.
If this isn't possible in Jackson, if you can't change pretty print options, then is there another popular JSON library that would do it?
Summary of options to change:
Don't open multiple containers on the same line
Don't close and open containers on the same line
Use 4 spaces as indents instead of 2
(another option, though I wouldn't use it) Open containers on a new line so that they line up vertically with their closing marker
Example of what it outputs now:
[ {
"id" : "12",
"payload" : [ {
"name" : "url",
"value" : [ {
"name" : "url",
"value" : "http://foobar.com"
} ]
}, {
"name" : "tags",
"value" : [ {
"name" : "tags",
"value" : "red"
}, {
"name" : "tags",
"value" : "green"
}, {
"name" : "tags",
"value" : "blue"
}, {
...
Example of what I'd like to get:
[
{
"id" : "12",
"payload" : [
{
"name" : "url",
"value" : [
{
"name" : "url",
"value" : "http://foobar.com"
}
]
},
{
"name" : "tags",
"value" : [
{
"name" : "tags",
"value" : "red"
},
{
"name" : "tags",
"value" : "green"
},
{
"name" : "tags",
"value" : "blue"
},
{
...
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