Extract single element from JSON
suggest changeimport com.google.gson.JsonObject;
import com.google.gson.JsonParser;
String json = "{\"name\": \"John\", \"age\":21}";
JsonObject jsonObject = new JsonParser().parse(json).getAsJsonObject();
System.out.println(jsonObject.get("name").getAsString()); //John
System.out.println(jsonObject.get("age").getAsInt()); //21
This uses Gson. get returns null when the name is absent, and the following getAsString or getAsInt then throws NullPointerException.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents