Leonar Aung Leonar Aung - 1 month ago 6
JSON Question

How to put json values to Android array?

It is my json string result =

{"a1":[{"Phone":"+959797715387","Pin":"744881"}],"a2":[{"Phone":"09772455728","Pin":"924543"}]}


and I parse the json by this code.

try {
JSONObject reader = new JSONObject(result);
JSONObject a1 = reader.getJSONObject("a1");
String Phone = a1.getString("Phone");
JSONObject a2 = reader.getJSONObject("a2");
String Pin = a2.getString("Pin");
txv1.setText(Phone+" "+Pin);
}
catch (Exception e) {
// TODO: handle exception
txv1.setText("Error");
}


Final Result is getting error from try/catch. Please help me to solve getting error and to store values in array. Thank you .

Answer

Your problem because the a1 & a2 is not JSONObject but JSONArray, so you can try this one solution:

public void parseJSON(String result) {
    try {
        JSONObject reader = new JSONObject(result);

        //this for value on a1
        JSONArray a1 = reader.getJSONArray("a1");
        String Phone_a1 = a1.getJSONObject(0).getString("Phone");
        String Pin_a1 = a1.getJSONObject(0).getString("Pin");

        //this for value on a2
        JSONArray a2 = reader.getJSONArray("a2");
        String Phone_a2 = a2.getJSONObject(0).getString("Phone");
        String Pin_a2 = a2.getJSONObject(0).getString("Pin");
    } catch (Exception e) {
        //your catch handle
    }
}