Java – How to parse JSON in Java

Java – How to parse JSON in Java

Lets assume you have a class Person with just a name.

private class Person {
    public String name;

    public Person(String name) { = name;

Google GSON (Maven)

Great JSON serialisation / de-serialisation of objects.

Gson g = new Gson();

Person person = g.fromJson("{\"name\": \"weblogiks\"}", Person.class);
System.out.println(; //weblogiks

System.out.println(g.toJson(person)); // {"name":"weblogiks"}

If you want to get a single attribute out you can do it easily with the Google library as well:

JsonObject jsonObject = new JsonParser().parse("{\"name\": \"weblogiks\"}").getAsJsonObject();

System.out.println(jsonObject.get("name").getAsString()); //weblogiks

Org.JSON (Maven)

If you don’t need object de-serialisation but to simply get an attribute, you can try org.json (or look GSON example above!)

JSONObject obj = new JSONObject("{\"name\": \"weblogiks\"}");

System.out.println(obj.getString("name")); //weblogiks

Jackson (Maven)

ObjectMapper mapper = new ObjectMapper();
Person user = mapper.readValue("{\"name\": \"weblogiks\"}", Person.class);

System.out.println(; //weblogiks




Leave a Reply

Your email address will not be published. Required fields are marked *