Adreamcathcer Adreamcatcher Adreamcathcer Adreamcatcher - 4 months ago 23
JSON Question

Android Studio passing JSON array and object

This is what the JSON looks like:

[{
"pmid": "2",
"name": " MANAGEMENT",
"result": "1",
"properties": [
{
"prop_id": "32",
"prop_name": "Bonneville",
"address": "122 Lakeshore",
"city": "Ripley",
"state": "OH",
"zip": "11454",
"lat": "41.123",
"long": "-85.5034"
}
]
}]


I am trying to parse it with the following Java in Android Studio:

JSONObject jObj = null;
try {
jObj = new JSONObject(jsonStr);


// We get weather info (This is an array)
JSONArray jArr = jObj.getJSONArray("properties");

// We use only the first value
//JSONObject JSONWeather = jArr.getJSONObject(0);
JSONObject c = jArr.getJSONObject(0);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
String phone = c.getString(TAG_PHONE);

} catch (JSONException e) {
e.printStackTrace();
}



return null;


I am not getting any results though. How can I successfully parse this JSON with Java through Android Studio?

Also, if there were multiple pieces to the array, how could we make sure each one of them is printed out?

Answer

Your JSON string start with JSONArray.

Here sample code, try it.

    JSONArray mJsonArray = new JSONArray(jsonStr);
    JSONObject mJsonObject = mJsonArray.getJSONObject(0);

    String pmid = mJsonObject.getString("pmid");
    String name = mJsonObject.getString("name");
    String result = mJsonObject.getString("result");


    JSONArray mJsonArrayProperty = mJsonObject.getJSONArray("properties");
    for (int i = 0; i < mJsonArrayProperty.length(); i++) {
        JSONObject mJsonObjectProperty = mJsonArrayProperty.getJSONObject(i);

        String prop_id = mJsonObjectProperty.getString("prop_id");
        String prop_name = mJsonObjectProperty.getString("prop_name");
        String address = mJsonObjectProperty.getString("address");
        String city = mJsonObjectProperty.getString("city");
        String state = mJsonObjectProperty.getString("state");
        String zip = mJsonObjectProperty.getString("zip");
        String lat = mJsonObjectProperty.getString("lat");
        String lon = mJsonObjectProperty.getString("long");
    }

Check Android JSON Parsing Tutorial

Comments