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!
We can parse a nested JSON object using the getString(index) method of JSONArray. This is a convenience method for the getJSONString(index). getString() method and it returns a string value at the specified position.
parse() The JSON. parse() method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned.
Use JSONObject keys() to get the key and then iterate each key to get to the dynamic value.
Roughly the code will look like:
// searchResult refers to the current element in the array "search_result" but whats searchResult? JSONObject questionMark = searchResult.getJSONObject("question_mark"); Iterator keys = questionMark.keys(); while(keys.hasNext()) { // loop to get the dynamic key String currentDynamicKey = (String)keys.next(); // get the value of the dynamic key JSONObject currentDynamicValue = questionMark.getJSONObject(currentDynamicKey); // do something here with the value... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With