59

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

4
  • 2
    'Show me the code' of what you've tried. Links to libs should be perfectly fine, you can learn on your own from there. If your question was "How do you parse JSON with XXX lib?", then your request for code is valid, otherwise, don't be afraid to experiment with something new.
    – Jesse Webb
    May 27, 2011 at 14:23
  • Was this issue resolved? Jun 17, 2011 at 3:49
  • try this import com.google.gson.JsonObject; import com.google.gson.JsonParser; JsonParser parser = new JsonParser(); JsonObject obj = parser.parse(jsonString).getAsJsonObject(); String age = obj.get("age").getAsString(); Apr 12, 2016 at 10:32
  • The question was closed (unjustifiably) so I will have to answer in a comment: add implementation('org.json:json:20230227') to your build.gradle, then int age = new JSONObject(yourJsonString).getInt("age") Jun 1, 2023 at 7:20

3 Answers 3

65

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.

5
  • 2
    The question was to find 'field', not age. The idea being a sub-key is required, not an immediate one.
    – Abby
    Feb 27, 2013 at 10:15
  • 5
    Actually I think the question was specifically how to find field 'age'.
    – devconsole
    Feb 27, 2013 at 16:43
  • Link is dead... Aug 25, 2017 at 9:50
  • @RobinDijkhof I have updated my answer
    – devconsole
    Aug 27, 2017 at 7:45
  • where is the 'getInt()' method
    – YourHelper
    Jan 16, 2022 at 23:01
10

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");
    }
  }
}
1
  • 3
    Good answer, but important thing to note here, I think, is that this approach of not creating a separate class for binding doesn't work if you're looking for nested fields (i.e. if he was looking for "field" instead of "age" he would've had to create a new class for binding)
    – stojke
    Jul 26, 2015 at 14:39
10

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.

1
  • If the desired field is a String and is present in the outermost json object, then can we simply use jsonObject.get("myStringField").toString(); instead of iterating the keySet ? Btw, thanks for mentioning the imports because so many projects have JSONObject.
    – MasterJoe
    May 9, 2019 at 0:02

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.