Extract single element from JSON

suggest change
import 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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents