-4

how can i parse such JSON string (but i have dynamic values)

{
 "data":{
         "dynamicValue1":{
                          "serial":"1",
                          "name":"ABC"
                         },
         "dynamicValue2":{
                          "serial":"2",
                          "name":"DEF"
                         },
         "dynamicValue3":{
                          "serial":"3",
                          "name":"GHI"
                         }
         }
}

most codes i saw before for static values, but i want help please thanks in advance.

  • to clarify: the node that is in your snippet **dynamicValue1** is in your real application some random value? – Radinator Nov 03 '16 at 09:27
  • If you can control the structure of your JSON, you should remove the dynamicValueN key and turn that into a JSON Array. -- http://pastebin.com/9ddpP8Lh – Knossos Nov 03 '16 at 09:28
  • 2
    or try this: http://stackoverflow.com/questions/7304002/how-to-parse-a-dynamic-json-key-in-a-nested-json-result – Radinator Nov 03 '16 at 09:29

3 Answers3

0

You can use a JSON Serializer like Jackson.

Frederick Eskens
  • 386
  • 3
  • 20
0

I suggest Use JSONObject keys() to get the key and then iterate each key to get to the dynamic value.

according to your json string code must be something look like this:-

//refers to the current element in the array "data"
JSONObject mainObj = new JSONObject(yourString);
JSONObject dynamicValue1 = mainObj.getJSONObject("dynamicValue1");
Iterator key = dynamicValue1.keys();

while(key.hasNext()) {
    // loop to get the dynamic key
    String currentDynamicKey = (String)key.next();

    //get value of the dynamic key
    JSONObject currentDynamicValue = dynamicValue1.getJSONObject(currentDynamicKey);

    // here do something  with the other value...
}

I suggest to you can try this solution.

Nitin Karande
  • 1,280
  • 14
  • 33
0

If you want to manual parsing then you can user iterator like..

                JSONObject mainObj = new JSONObject(yourString);
                JSONObject dynamicObj = mainObj.getJSONObject("data");
                        jObject = new JSONObject(dynamicObj .toString());
                                Iterator<?> keys = jObject.keys();
                                while (keys.hasNext()) {
                                   String key = (String) keys.next();
                                    JSONObject  mainObj=jObject.getJSonOject(key);                              
                               String serialValue=mainObj.optString("serial")
                               String nameValue=mainObj.optString("name")

                                }