How to find specified name and its value in JSON-string from 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, … Read more

Decode JSON string in Java with json-simple library

This is the best and easiest code: public class test { public static void main(String str[]) { String jsonString = “{\”stat\”: { \”sdr\”: \”aa:bb:cc:dd:ee:ff\”, \”rcv\”: \”aa:bb:cc:dd:ee:ff\”, \”time\”: \”UTC in millis\”, \”type\”: 1, \”subt\”: 1, \”argv\”: [{\”type\”: 1, \”val\”:\”stackoverflow\”}]}}”; JSONObject jsonObject = new JSONObject(jsonString); JSONObject newJSON = jsonObject.getJSONObject(“stat”); System.out.println(newJSON.toString()); jsonObject = new JSONObject(newJSON.toString()); System.out.println(jsonObject.getString(“rcv”)); System.out.println(jsonObject.getJSONArray(“argv”)); } … Read more

Pretty-Print JSON in Java

Google’s GSON can do this in a nice way: Gson gson = new GsonBuilder().setPrettyPrinting().create(); JsonParser jp = new JsonParser(); JsonElement je = jp.parse(uglyJsonString); String prettyJsonString = gson.toJson(je); or since it is now recommended to use the static parse method from JsonParser you can also use this instead: Gson gson = new GsonBuilder().setPrettyPrinting().create(); JsonElement je = … Read more