简体   繁体   中英

How to get the value from this json string in java?

I have the below json string as output,

{"message":"Error while updating","success":false}

And i am trying to get the json object out of it by using,

String resp = "{"message":"Error while updating",
                   "success":false}";
JSONObject jObject  = new JSONObject(resp);
log.info("jObject-success: "+ jObject.getString("success").toString());

The above line throws "success" is not found in the response error. What am i missing here?

You are writing your JSON string wrong. use escape character.

Ex:

String s = "[0,{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}]";

for your code

String resp = "{\"message\":\"Error while updating\",\"success\":false}";

Let's create a class representing your JSON input

public class Response {
    public String  message;
    public boolean success;
}

and use Google's gson library as follows to parse it

Gson gson = new Gson();
Response response = gson.fromJson(resp, Response.class);
System.out.println("Success: " + response.success);

Let's assume you define resp properly and your code compiles.

I am also assuming your are using org.json.JSONObject

You will need to use jObject.getBoolean("success").toString() . I recall that getString() in JSONObject will throw exception if the field is not type of string.

String resp = string output;

JSONObject object = new JSONObject(resp);

System.out.println(object.get("message"));

System.out.println(object.get("success"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM