Here I am going to show you how to convert JSON to Java Object using Jackson.

JSON to Java object :

In the previous tutorials we have seen how to convert a Java object to JSON string, you can see the dependencies of Jackson their.

[java]

package com.onlinetutorialspoint.json;

import org.codehaus.jackson.map.ObjectMapper;

public class JSON_String_To_Java_Object {
    public static void main(String[] a) {

        ObjectMapper mapperObj = new ObjectMapper();
        try {
            Student studentObj2 = mapperObj.readValue(jsonString(),
                    Student.class);
            System.out.println(studentObj2);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String jsonString() {
        String str = "{\"studentId\": 1001, \"studentName\": \"Rahul\","
                + "\"roleNumber\": \"105\",\"standard\": \"5th\"}";
        return str;

    }
}
[/java]

[box type=”success” align=”alignleft” class=”” width=”100%”]
Student [studentId=1001, studentName=Rahul, roleNumber=105, standard=5th]

[/box]

JSON to Java object Reading from File :

Here I am going to read JSON string from a file and converting as Java object.

json.txt

[text]

{
"studentId": 4001,
"studentName": "Santosh",
"roleNumber": "107",
"standard": "7th"
}

[/text]

Reading JSON string from above file and converting to Java object.

[java]

package com.onlinetutorialspoint.json;

import java.io.File;

import org.codehaus.jackson.map.ObjectMapper;

public class JSON_String_To_Java_Object {
    public static void main(String[] a) {

        ObjectMapper mapperObj = new ObjectMapper();
        String filePath = "/json.txt";
        try {
            File file = new File(filePath);
            Student studentObj = mapperObj.readValue(file, Student.class);
            System.out.println(studentObj);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

[/java]

[box type=”success” align=”alignleft” class=”” width=”100%”]
Student [studentId=4001, studentName=Santosh, roleNumber=107, standard=7th]
[/box]

Happy Learning 🙂

About the Author:

Founder of onlinetutorialspoint.com Love Java, Python, Shell and opensource frameworks. Follow him on twitter and facebook for latest updates.

Leave A Comment