How to convert json file to java object in spring boot

What you will learn here about Spring boot

  • How to convert json file to java object in spring boot

How to convert json file to java object in spring boot

Please follow the following steps to know how to convert json file to java object in spring boot
1)First create simple maven or Spring boot project

2)Add jackson dependency in your pom.xml which is shown below

<dependency>
     <groupId>com.fasterxml.jackson.core</groupId>
     <artifactId>jackson-databind</artifactId>
     <version>2.7.4</version>
</dependency>

Spring boot jackson dependency

3)Now create json file under resources path which is shown below
spring boot json file

4)Now create POJO with respect to your json file which is shown below
spring boot convert json file to java object

5)With Object mapper we can convert json file to java object which is shown below
How to convert json file to java object in spring boot

import java.io.File;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

public class MainApp {

    public static void main(String[] args) {
       Person person = new Person();
        
       person = json2Java("person.json", Person.class);
       System.out.println(person.getEmail());
    }

    public static <T> T json2Java(String fileName, Class<T> classType){

    	T t = null;
    	File file = new File("src/main/resources/"+fileName);
    	
    	 try {
    		 ObjectMapper mapper = new ObjectMapper();
    	    mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
			t=mapper.readValue(file, classType);
		}catch (Exception e) {
			e.printStackTrace();
		}
    	 
        return t;
    }
}

You may also like...