-3

I have a jsonElement as following how can I retrieve "value2" with minimal amount of coding?

{
  "key1": "value1",
  "key2": "value2",
  "key3": "value3"
}
Waterfr Villa
  • 1,217
  • 1
  • 10
  • 33

1 Answers1

1

Add jar in your project : org.json.

Suppose that you are having string,

String yourString = "{ \"key1\": \"value1\",\"key2\": \"value2\",\"key3\":\"value3\" }"

JSONObject jsonObj = new JSONObject(yourString);

First of all, check the desired key which you want to access to avoid nullPointer exception , then access you value . i.e.

Note: It is always a good practice to check whether this exists but in your case not mandatory

if(jsonObj.contains("key2") {  

 String key2 = jsonObj.getString("key2");
}
Vishwa Ratna
  • 5,567
  • 5
  • 33
  • 55
ASK
  • 1,136
  • 1
  • 10
  • 14