Languages
[Edit]
EN

Java - parse JSON to object with Jackson lib

5 points
Created by:
Root-ssh
75620

In this short article we would like to show how to convert JSON to Java object, using external Jackson library.

Quick solution:

// import com.fasterxml.jackson.core.JsonProcessingException;
// import com.fasterxml.jackson.databind.ObjectMapper;

ObjectMapper objectMapper = new ObjectMapper();

String userJson = "{\"name\":\"John\",\"age\":21}";
User userObject = objectMapper.readValue(userJson, User.class);

System.out.println(userObject.getName()); // John
System.out.println(userObject.getAge());  // 21

Hint: to know how to attach *.jar lib to out project read this article.

Link to library in Maven repository:
https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind

Note: if you want to convert Object to JSON String read this article.

Full example how to use Jackson library

Main.java file content:

package examples;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Main {

    public static void main(String[] arg) throws JsonProcessingException {

        ObjectMapper objectMapper = new ObjectMapper();

        String userJson = "{\"name\":\"John\",\"age\":21}";
        User userObject = objectMapper.readValue(userJson, User.class);

        System.out.println(userObject.getName()); // John
        System.out.println(userObject.getAge());  // 21
    }
}

Example output:

John
21

User.java file content:

package examples;

public static class User {

    private String name;
    private int age;

    // required no-arguments constructor
    public User() {
        // nothing here ...
    }

    public String getName() {
        return this.name;
    }

    public int getAge() {
        return this.age;
    }
}

Java JSON - Jackson lib

Native Advertising
­čÜÇ
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - friendly IT community for everyone.

ÔŁĄ´ŞĆ­čĺ╗ ­čÖé

Join