0

This is the response.

{
  "code": 200,
  "data": {
    "createdAt": "2019-12-09 15:21:07.0",
    "id": 3,
    "title": "{\"v\":\"1\"}",
    "token": "INACTIVE"
  },
  "message": "SUCCESS"
}

I need value of v which is 1. I'm getting this

{"v":"1"}

through

JSONObject r2 = new JSONObject(operation);
                String title = r2.getString("title");
                System.out.println(title);

How do I get the value of v after this? It would be great if I could get any suggestions.

2 Answers 2

2

The value of title is a string with JSON text, so you need to re-invoke the JSON parser.

Also, in the question code, you forgot to navigate past the data node.

JSONObject rootObj = new JSONObject(operation); // parse JSON text
String title = rootObj.getJSONObject("data").getString("title"); // get "title" value
JSONObject titleObj = new JSONObject(title); // parse JSON text
String v = titleObj.getString("v"); // get "v" value
System.out.println(v); // prints: 1
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a bunch, got your logic.
1
String v= r2.getJSONObject("title").getString("v");
System.out.println(v);

PS: Don't forget to handle nulls,etc.

UPDATE: Please refer Andreas's answer as it is the correct answer. This answer wrongly assumes that title also contains json.

6 Comments

getString option does not even appear in suggestion. Not working.
The value of title is not a JSON object, but a string. The string content just happens to be another JSON text.
In the code snippet you have provided, you are calling calling getString on r2 object which is of type JSONObject which is same as in the answer I have provided.
getting an error, saying title is not a json object
@SubhaBhowmik Because title is not a JSON object, and this answer doesn't work, for the reason I already stated. Don't know why it has been upvoted. See here for working solution.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.