0

Trying to parse this type of json format in java

{
"output": "success",
"result": [
    {
        "id": 1,
        "label": "name",

    },
    {
        "id": 2,
        "label": "name_2",

    }
]
}

I am getting this type of json format, now what i want to do is check first if output.equalsIgnoreCase("success)" if true then parse the second array of result. And this is i tried so far.

try {
  JSONArray myJson = new JSONArray(response);
  String status = myJson.getString(Integer.parseInt("output"));
  if(status.equalsIgnoreCase("success")) {
    for (int i = 0; i < myJson.length(); i++) {
      JSONObject obj = myJson.getJSONObject(i);
      name.add(obj.getString("label"));
    }
    Log.e("list" , name.toString());
  }
} catch (Exception e) {
}
Roddy of the Frozen Peas
  • 14,380
  • 9
  • 49
  • 99

2 Answers2

0
    String responceStr = ...; // here is your full responce string
    try {
        JSONObject responce = new JSONObject(responceStr);
        String status = responce.getString("output");
        if ("success".equalsIgnoreCase(status)) {
            JSONArray result = responce.getJSONArray("result");
            for (int i=0; i < result.length(); i++){
                JSONObject jsonPair = result.getJSONObject(i);
                int id = jsonPair.getInt("id");
                String label = jsonPair.getString("label");
            }
        }
    } catch (JSONException e){

    }

Integer.parseInt("123") -- is OK.

Integer.parseInt("output") -- is NOT OK.

because Integer.parseInt() parses the string representation of an integer. "output" string does not represent an integer.

babay
  • 4,689
  • 1
  • 26
  • 40
0

The response is a JSONObject, not JSONArray (it is enclosed between curly brackets). The array is the field named result. So change myJson to JSONObject and after checking the success field, create a new variable

 JSONArray resultArray = myJson.getArray("result");

and iterate over this instead of myJson. Also you should not discard the exception since the stacktrace could provide some hint about the problems. You can add

e.printStackTrace();

in the catch block.

Crispert
  • 1,102
  • 7
  • 13