Monday , September 25 2017
Home / json / How to convert JSON to Java Object Example

How to convert JSON to Java Object Example

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.


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;

    }
}
Student [studentId=1001, studentName=Rahul, roleNumber=105, standard=5th]

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


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

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


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

Student [studentId=4001, studentName=Santosh, roleNumber=107, standard=7th]

Happy Learning 🙂

About chandrashekhar

Hi Folks, you have reach this so far, that shows you like what you are learning. Then why don't you support us to improve for bettor tutorials by leaving your valuable comments and why not you keep in touch with us for latest updates on your favorite blog @ facebook , twitter , Or Google+ ,

Recommended

How to convert Java Map to JSON

Here I am going to show you how to convert a Java Map to JSON …

Leave a Reply

Your email address will not be published. Required fields are marked *