Friday, June 1, 2018

Parsing JSON in Java

Lets assume you have a class Person with just a name.
private class Person {
    public String name;

    public Person(String name) {
        this.name = name;
    }
}

Google GSON (Maven)

One great is JSON serialisation / de-serialisation of objects.
Gson g = new Gson();

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

System.out.println(g.toJson(person)); // {"name":"John"}
Update
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\": \"John\"}").getAsJsonObject();

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

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\": \"John\"}");

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

Jackson (Maven)

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

System.out.println(user.name); //John

4 comments:

Interview Prep: Java full stack

 SOLID principle :  https://www.educative.io/answers/what-are-the-solid-principles-in-java Design Pattern:  Creational:  https://medium.com...