Jackson Annotations - @JsonProperty
Overview
@JsonProperty annotation is used at mark a property of special type to be ignored.
Example - Deserialization without using @JsonProperty
JacksonTester.java
package com.tutorialspoint;
import java.io.IOException;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonTester {
public static void main(String args[]) throws IOException {
ObjectMapper mapper = new ObjectMapper();
String json = "{\"id\" : 1}";
Student student = mapper.readerFor(Student.class).readValue(json);
System.out.println(student.getTheId());
}
}
class Student {
private int id;
Student(){}
Student(int id){
this.id = id;
}
public int getTheId() {
return id;
}
public void setTheId(int id) {
this.id = id;
}
}
Output
Run the JacksonTester and verify the output −
1
Example - Deserialization with @JsonProperty
JacksonTester.java
package com.tutorialspoint;
import java.io.IOException;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonTester {
public static void main(String args[]) throws IOException {
ObjectMapper mapper = new ObjectMapper();
String json = "{\"id\" : 1}";
Student student = mapper.readerFor(Student.class).readValue(json);
System.out.println(student.getTheId());
}
}
class Student {
private int id;
Student(){}
Student(int id){
this.id = id;
}
@JsonProperty("id")
public int getTheId() {
return id;
}
@JsonProperty("id")
public void setTheId(int id) {
this.id = id;
}
}
Output
Run the JacksonTester and verify the output −
1
Here we can see, even without using @JsonProperty, Jackson is deserializing using the available setter method. Use of @JsonProperty is recommended where we've custom setter methods instead of standard setter methods.
Advertisements