How to use json with java


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’:

Maven 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();

        String json = gson.toJson(person);

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);

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