How to find specified name and its value in JSON-string from Java?

Roman picture Roman · May 27, 2011 · Viewed 150.5k times · Source

Let's assume we have the next JSON string:

{  
   "name" : "John",
   "age" : "20",
   "address" : "some address",
   "someobject" : {
       "field" : "value"    
   }
}

What is the easiest (but still correct, i.e. regular expressions are not acceptable) way to find field age and its value (or determine that there's no field with given name)?

p.s. any open-source libs are ok.

p.s.2: please, don't post links to the libraries - it's not a useful answer. 'Show me the code'(c).

Answer

devconsole picture devconsole · May 27, 2011

Use a JSON library to parse the string and retrieve the value.

The following very basic example uses the built-in JSON parser from Android.

String jsonString = "{ \"name\" : \"John\", \"age\" : \"20\", \"address\" : \"some address\" }";
JSONObject jsonObject = new JSONObject(jsonString);
int age = jsonObject.getInt("age");

More advanced JSON libraries, such as jackson, google-gson, json-io or genson, allow you to convert JSON objects to Java objects directly.