57

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

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Roman
  • 64,384
  • 92
  • 238
  • 332
  • 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 '11 at 14:23
  • Was this issue resolved? – Programmer Bruce Jun 17 '11 at 03: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(); – Suliman Alzamel Apr 12 '16 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")` – Marco Lackovic Jun 01 '23 at 07:20

3 Answers3

63

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.

devconsole
  • 7,875
  • 1
  • 34
  • 42
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");
    }
  }
}
Programmer Bruce
  • 64,977
  • 7
  • 99
  • 97
  • 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 '15 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.

philipjkim
  • 3,999
  • 7
  • 35
  • 48
  • 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 09 '19 at 00:02