How to parse this json with multiple objects

Tags: , , ,



devs I am stuck in parsing this kind of JSON I don’t understand how to get the value of status and message any help will be very appreciable. I get the value of error but when I want to access the value of status and message it throws an error JSON Format :

{
    "error": {
        "status": 400,
        "message": "Wrong number of segments"
    }
}

My code for parsing json :

  try {
                    JSONObject jso = new JSONObject(String.valueOf(response));

                    //jso.getJSONObject("error").getJSONObject("message");
                   jso.getJSONObject("error");
                   jso.getJSONObject("status").toString(200);
                    Log.d(TAG,"jso1"+jso);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

Answer

JSONParser parser = new JSONParser();
JSONObject jso = (JSONObject) parser.parse(String.valueOf(response));

The above command will give you the response as JSON.

To get Status and message, you need to extract error as a separate JSONObject and then parse status and message

JSONObject errorObj = (JSONObject) jso.get("error");
String message = errorObj.get("message").toString();
int status = Integer.parseInt(errorObj.get("status").toString());

Remember to parse and retrieve using the hierarchy.. so if the status & message are inside “error”, then extract error as a JSONObject and then retrieve the child keys. And as a good practice check if the key exists or not:-

if(errorObj.has("")) {
// do something
}

Adding a working sample :-

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser; 
private static void parseJsonTest() {
            String json = "{n" +
                    "    "error": {n" +
                    "        "status": 400,n" +
                    "        "message": "Wrong number of segments"n" +
                    "    }n" +
                    "}";
            try {
                JSONParser parser = new JSONParser();
    
                JSONObject jso = (JSONObject) parser.parse(json);
    
                JSONObject errorObj = (JSONObject) jso.get("error");
                String message = errorObj.get("message").toString();
                int status = Integer.parseInt(errorObj.get("status").toString());
    
                System.out.println(message + " >>>>>>> " + status);
            } catch (Exception e) {
    
            }
        }

Output :-

Wrong number of segments >>>>>>> 400


Source: stackoverflow