Convert Json to Java object using Jackson library

I published a post on "how to convert java object into the json format. In case you missed it, click here for your reference. Today, we are going to reverse that, meaning from the json file we are going to read and convert that into the java object.

We have the json file in the local machine user.json

user.json

{"messages":["Your name is - Amzi","Your Id is - 1","Welcome to the world!!!"],"name":"Amzi","id":1}


I'd assume that you already have the required jackson library in your project class path. I described that in my previous post in detail.

Now, lets create the java file which will read json file and create the java object out of it. For that we are going to use the readValue() method which is available in ObjectMapper class. ObjectMapper class is the part of the jackson library.

Json2Java.java

package com.amzi.java;

import java.io.File;
import java.io.IOException;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

public class Json2Java {

    public static void main(String[] args) {

        ObjectMapper mapper = new ObjectMapper();
        try {
            // read from file, convert it to user class
            User user = mapper.readValue(new File(
                    "c:\\Users\\Amzi\\Desktop\\user.json"), User.class);

            // display to console
            System.out.println(user);

        } catch (JsonGenerationException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


Output:

User [id=1, name=Amzi, messages=[Your name is - Amzi, Your Id is - 1, Welcome to the world!!!]]

No comments:

Post a Comment