Jackson Custom field name with @JsonProperty

When the JSON field name doesn’t exactly match the Java field names, we can use @JsonProperty to change the name of a JSON field in Jackson.

Table of contents:

P.S Tested with Jackson 2.17.0

1. Setup Jackson

Puts jackson-databind at pom.xml.

pom.xml

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

2. JSON Unrecognized field

Review below JSON data, the JSON field name nick_name doesn’t match the Person name. If we use Jackson to do the data binding, it will hits error like Unrecognized field "nick_name".


{
  "nick_name": "mkyong",
  "age": 42
}
Person.java

public class Person {

    private String name;
    private int age;

    //getters, setters, constructors and etc...
}

3. Custom field name with @JsonProperty

To fix it, we can use @JsonProperty to change the matching field name of the JSON in Jackson.

Person.java

import com.fasterxml.jackson.annotation.JsonProperty;

public class Person {

    @JsonProperty("nick_name")
    private String name;
    private int age;

    //getters, setters, constructors and etc...
}
CustomFieldNameExample.java

package com.mkyong.json.jackson.tips;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mkyong.json.model.Person;

public class CustomFieldNameExample {

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

        ObjectMapper mapper = new ObjectMapper();

        String json = "{\"nick_name\":\"mkyong\",\"age\":42}";

        Person person = mapper.readValue(json, Person.class);

        System.out.println(person);

        String newJson = mapper.writeValueAsString(person);

        System.out.println(newJson);

    }

}

Output


Person{name='mkyong', age=42}

{"age":42,"nick_name":"mkyong"}

4. Download Source Code

$ git clone https://github.com/mkyong/java-json

$ cd jackson

5. References

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments