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

JavaJsonGsonJson Simple

Java Problem Overview


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

Java Solutions


Solution 1 - Java

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.

Solution 2 - Java

Gson allows for one of the simplest possible solutions. Compared to similar APIs like Jackson or svenson, Gson by default doesn't even need the unused JSON elements to have bindings available in the Java structure. Specific to the question asked, here's a working solution.

import com.google.gson.Gson;

public class Foo
{
  static String jsonInput = 
    "{" + 
      "\"name\":\"John\"," + 
      "\"age\":\"20\"," + 
      "\"address\":\"some address\"," + 
      "\"someobject\":" +
      "{" + 
        "\"field\":\"value\"" + 
      "}" + 
    "}";
  
  String age;
  
  public static void main(String[] args) throws Exception
  {
    Gson gson = new Gson();
    Foo thing = gson.fromJson(jsonInput, Foo.class);
    if (thing.age != null)
    {
      System.out.println("age is " + thing.age);
    }
    else
    {
      System.out.println("age element not present or value is null");
    }
  }
}

Solution 3 - Java

I agree that Google's Gson is clear and easy to use. But you should create a result class for getting an instance from JSON string. If you can't clarify the result class, use json-simple:

// import static org.hamcrest.CoreMatchers.is;
// import static org.junit.Assert.assertThat;
// import org.json.simple.JSONObject;
// import org.json.simple.JSONValue;
// import org.junit.Test;

@Test
public void json2Object() {
	// given
	String jsonString = "{\"name\" : \"John\",\"age\" : \"20\","
			+ "\"address\" : \"some address\","
			+ "\"someobject\" : {\"field\" : \"value\"}}";

	// when
	JSONObject object = (JSONObject) JSONValue.parse(jsonString);

	// then
	@SuppressWarnings("unchecked")
	Set<String> keySet = object.keySet();
	for (String key : keySet) {
		Object value = object.get(key);
		System.out.printf("%s=%s (%s)\n", key, value, value.getClass()
				.getSimpleName());
	}

	assertThat(object.get("age").toString(), is("20"));
}

Pros and cons of Gson and json-simple is pretty much like pros and cons of user-defined Java Object and Map. The object you define is clear for all fields (name and type), but less flexible than Map.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRomanView Question on Stackoverflow
Solution 1 - JavadevconsoleView Answer on Stackoverflow
Solution 2 - JavaProgrammer BruceView Answer on Stackoverflow
Solution 3 - JavaphilipjkimView Answer on Stackoverflow