0
{
    "Items": [{
            "__type": "Section1:#com.test.example",
            "Info": {            
            }, {
            "__type": "Section2:#com.test.example2",
            "Allergy": [{


            }]

            }
      }]

}

How can i parse the above JSON Object, so that i get Info items and Allergy items....

JSONObject documentRoot = new JSONObject(result);
JSONArray documentChild = documentRoot.getJSONArray("Items");
JSONObject child = null;
for (int i = 0; i < documentChild.length(); i++) {
    child = documentChild.getJSONObject(i);

}
2
  • 3
    What you pasted above is not valid JSON. Can you copy/paste from the valid JSON source directly? Commented Apr 13, 2013 at 22:54
  • 1
    Take a look at Gson for that kind of stuff. Gets as easy as Gson.fromJson() to get objects out of a JSON String. Anyway the JSON indeed looks malformed. Commented Apr 13, 2013 at 22:57

1 Answer 1

2

This is the valid JSON : Check validity here :http://jsonlint.com/

{
    "Items": [
        {
            "__type": "Section1:#com.test.example",
            "Info": {}
        },
        {
            "__type": "Section2:#com.test.example2",
            "Allergy": [
                {}
            ]
        }
    ]
}

Try :

public static final String TYPE_KEY = "__type";
public static final String TYPE1_VAUE = "Section1:#com.test.example";
public static final String TYPE2_VAUE = "Section2:#com.test.example2";


public static final String INFO_KEY = "Info";
public static final String ALLERGY_KEY = "Allergy";

....

String infoString = null;
JSONArray allergyArray = null;

for (int i = 0; i < documentChild.length(); i++) {
    child = documentChild.getJSONObject(i);

    final String typeValue = child.getString(TYPE_KEY);

    if(TYPE1.equals(typeValue)) {
        infoString = child.getString(INFO_KEY);
    }else if(TYPE2.equals(typeValue)) {
        allergyArray = child.getJSONArray(ALLERGY_KEY);
    }
}

if(null != infoString) {
    // access the 'Info' value in 'infoString'
}

if(null != allergyArray) {
    // access the 'Allergy' array in 'allergyArray'
}

...

Hope this helps!

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.