Friday 19 May 2023

Jackson: @JsonCreator annotation example

@JsonCreator annotation can be applied on constructor and factory methods and used  for instantiating new instances of the associated class.

 

Every argument of @JsonCreator annotated method is annotated with either JsonProperty or JacksonInject, to indicate name of property to bind to.

 

Example

public class Employee3 {

    private int id;
    private String name;
    private int age;

    @JsonCreator
    public Employee3(@JsonProperty("emp_id") int id, @JsonProperty("emp_name") String name, 
            @JsonProperty("age")int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    .....
    .....
}

 

Find the below working application.

 


Employee3.java
package com.sample.app.model;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;

public class Employee3 {

    private int id;
    private String name;
    private int age;

    @JsonCreator
    public Employee3(@JsonProperty("emp_id") int id, @JsonProperty("emp_name") String name,
            @JsonProperty("age") int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Employee3 [id=" + id + ", name=" + name + ", age=" + age + "]";
    }

}

 

JsonCreatorDemo.java

package com.sample.app;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sample.app.model.Employee3;

public class JsonCreatorDemo {

    public static void main(String[] args) throws JsonProcessingException {

        ObjectMapper objectMapper = new ObjectMapper();

        String inputJson = "{\"emp_id\":1,\"emp_name\":\"Krishna\",\"age\":34}";
        System.out.println("Deserializing the json : " + inputJson);
        Employee3 deserializedObj = objectMapper.readValue(inputJson, Employee3.class);
        System.out.println(deserializedObj);

        System.out.println("\nSerializing the object to json");
        String json = objectMapper.writeValueAsString(deserializedObj);
        System.out.println(json);
    }

}

 

Output

Deserializing the json : {"emp_id":1,"emp_name":"Krishna","age":34}
Employee3 [id=1, name=Krishna, age=34]

Serializing the object to json
{"age":34,"id":1,"name":"Krishna"}

 

   

Previous                                                 Next                                                 Home

No comments:

Post a Comment