How to use json with java

H

Is it possible to use json in combination with java? The answer is yes! You can easily parse json objects to java objects and vice-versa. To do so, you can use Google’s framework ‘gson’: http://code.google.com/p/google-gson/

Maven dependency

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.2.4</version>
</dependency>

We make a java model class ‘Person’. That person has a first name and a last name:

public class Person {

    private String firstname;
    private String lastname;

    //getters and setters
    ...

    public String toString() {
        return "Person [firstname: "+ firstname + ", lastname: " + lastname + "]";
    }
}

Now we can create a person object and parse it to a json string with gson:

public class PersonToJson {

    public static void main(String[] args) {

        Person person = new Person();
        person.setFirstname("Laurent");
        person.setLastname("Hinoul");

        String json = gson.toJson(person);
        System.out.println(json);
    }
}

The output will be: {“firstname”:”Laurent”,”lastname”:”Hinoul”}

Now we can easily parse that string back to an object:

public class JsonToPerson {

    public static void main(String[] args) {

        final String json = "{"firstname":"Laurent","lastname":"Hinoul"}";
        Gson gson = new Gson();
        Person person = gson.fromJson(json, Person.class);
        System.out.println(person);
    }
}

The output will be: Person [firstname: Laurent, lastname: Hinoul]

Add comment

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Tag Cloud

Categories