Tuesday 14 March 2023

Jackson: Use different property names for serialization and deserialization

In this post, I am going to explain how to use different property names for the serialization and deserialization using JsonGetter and JsonSetter annotations.

 


Example

public class Employee {

    private String firstName;

    // # Used during serialization
    @JsonGetter("fname")
    public String getFirstName() {
        return firstName;
    }

    // # Used during deserialization
    @JsonSetter("fn")
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
}

Above snippet generate the property fname during serialization and populate the property firstName from the json property fn during deserialization.

 

Find the below working application.

 

Employee.java

package com.sample.app.model;

import com.fasterxml.jackson.annotation.JsonGetter;
import com.fasterxml.jackson.annotation.JsonSetter;

public class Employee {

    private Integer id;

    private String firstName;

    private String lastName;

    public Integer getId() {
        return id;
    }

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

    // # Used during serialization
    @JsonGetter("fname")
    public String getFirstName() {
        return firstName;
    }

    // # Used during deserialization
    @JsonSetter("fn")
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    // # Used during serialization
    @JsonGetter("lname")
    public String getLastName() {
        return lastName;
    }

    // # Used during deserialization
    @JsonSetter("ln")
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    @Override
    public String toString() {
        return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + "]";
    }

}

JsonGetterAndSetterDemo.java

package com.sample.app;

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

public class JsonGetterAndSetterDemo {

    public static void main(String[] args) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();

        Employee emp = new Employee();
        emp.setId(1);
        emp.setFirstName("Krishna");
        emp.setLastName("Gurram");

        String json = objectMapper.writeValueAsString(emp);
        System.out.println(json);

        String jsonInput = "{\"id\":1,\"fn\":\"Krishna\",\"ln\":\"Gurram\"}";
        Employee deserializedEmp = objectMapper.readValue(jsonInput, Employee.class);
        System.out.println(deserializedEmp);
    }

}

Output

{"id":1,"fname":"Krishna","lname":"Gurram"}
Employee [id=1, firstName=Krishna, lastName=Gurram]

 

Previous                                                 Next                                                 Home

No comments:

Post a Comment