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).
To extract the scalar value from the JSON string, use the json_extract_scalar function. It is similar to json_extract , but returns only scalar values (Boolean, number, or string).
You can escape String in Java by putting a backslash in double quotes e.g. " can be escaped as \" if it occurs inside String itself. This is ok for a small JSON String but manually replacing each double quote with an escape character for even a medium-size JSON is time taking, boring, and error-prone.
You can get the object from the JSON with the help of JSONObject. get() method and then using the instanceof operator to check for the type of Object. Note that it may be Integer or Long ; Float or Double .
Use below code to find key is exist or not in JsonObject . has("key") method is used to find keys in JsonObject . If you are using optString("key") method to get String value then don't worry about keys are existing or not in the JsonObject . Note that you can check only root keys with has(). Get values with get().
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.
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"); } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With