I have a JSON result in the following format which JSON Lint shows this as a "Valid Response".
My question is: how do I access the content of "question_mark" since "141", "8911", etc are all dynamic values?
My sample code for accessing value of "product".
//Consider I have the first <code>JSONObject</code> of the "search_result" array and
//I access it's "product" value as below.
String product = jsonObject.optString("product"); //where jsonObject is of type JSONObject.
//<code>product<code> now contains "abc".
JSON:
{
"status": "OK",
"search_result": [
{
"product": "abc",
"id": "1132",
"question_mark": {
"141": {
"count": "141",
"more_description": "this is abc",
"seq": "2"
},
"8911": {
"count": "8911",
"more_desc": "this is cup",
"seq": "1"
}
},
"name": "some name",
"description": "This is some product"
},
{
"product": "XYZ",
"id": "1129",
"question_mark": {
"379": {
"count": "379",
"more_desc": "this is xyz",
"seq": "5"
},
"845": {
"count": "845",
"more_desc": "this is table",
"seq": "6"
},
"12383": {
"count": "12383",
"more_desc": "Jumbo",
"seq": "4"
},
"257258": {
"count": "257258",
"more_desc": "large",
"seq": "1"
}
},
"name": "some other name",
"description": "this is some other product"
}
]
}
My question title "dynamic key" could be wrong but I don't know at this point what's a better name for this issue.
Any help would be greatly appreciated!
Use JSONObject keys() to get the key and then iterate each key to get to the dynamic value.
Roughly the code will look like:
The same thing can also be done using GSON, but instead of using GSON converter adapter to convert into to POJO. we will parse it manually. which gives us flexibility in case of dynamic JSON data.
let's say the JSON format is like below in my case.
in this case the dateWiseContent has dynamic object keys so we will parse this json string using JsonParser class.
get the dynamic keys using
Map.Entry<String, JsonElement>
as given belowsimilarly any level of dynamic json can be parsed using
Map.Entry<String,JsonElement>
An example of using Google Gson
JSON data from the question:
Example code:
Output:
Another possibility is to use Gson (Note, I use lombok here to generates getters/setters, toString, etc):
Output: