Sunday, December 12, 2021

How jackson convert json to pojo?

 By default jackson use appropriate getter and setter method to bind data .

lets see and example ,

Json to pojo--



let's see a practical example-

we have a file containing a json object representing student . Then read json object from the file and convert it to student object.

.import java.io.File;

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

public class MainApp{

  public static void main(String[] args){

           ObjectMapper objectMapper  = new ObjectMapper();

           Student student = objectMapper.readValue(new File("sample.json"),Student.class);

        }

}

In this example objectMapper will read value from sample.json file and convert that json object into student object using corresponding setter methods.

N.B:When we converting json to pojo it will call setter but in vice versa it will call getter .But what if the corresponding getter and setter are not found then it will throw exception . So how we can avoid some property if needed .Then we can use special annotation -

@JsonIgnoreProperties(ignoreUnknown=true)

public class Student{

    private int id;//has setter and getter

    private String firstName;//has setter and getter

    private String lastName;

}

No comments:

Post a Comment

Fluent interface pattern

 public class UserConfigurationManager {     private String userName;     private String password;     private UserConfigurationManager() { ...