coderman
coderman

Reputation: 355

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?

Upvotes: 0

Views: 499

Answers (4)

user3467480
user3467480

Reputation: 93

String resp = string output;

JSONObject object = new JSONObject(resp);

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

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

Upvotes: 0

Alvin
Alvin

Reputation: 10458

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.

Upvotes: 0

AKS
AKS

Reputation: 19801

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);

Upvotes: 0

Deepu--Java
Deepu--Java

Reputation: 3820

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}";

Upvotes: 3

Related Questions