@JsonValue annotation is used to indicate that the return value of annotated method (with no args) is to be used as the single value to serialize rather than collecting all properties of the object. Usually the getter should return a simple scalar type (e.g. String or Number), but it can be any serializable type. This annotation can also be used on the methods like toString().
Starting version 2.9 this annotation can be used on fields as well.
Example
POJO
public class Person {
private String name;
private int age;
.............
@JsonValue
public String toPersonInfo() {
return name + " - " + age;
}
.............
}
Serializing
public class ExampleMain {
public static void main(String[] args) throws IOException {
Person person = new Person("Jessie", 35);
System.out.println("-- before serialization --");
System.out.println(person);
ObjectMapper om = new ObjectMapper();
String jsonString = om.writeValueAsString(person);
System.out.println("-- after serialization --");
System.out.println(jsonString);
}
} -- before serialization -- Person{name='Jessie', age=35} -- after serialization -- "Jessie - 35"
Using @JsonValue on field
public class Person2 {
private String name;
private int age;
@JsonValue
private String personInfo;
.............
}
public class ExampleMain2 {
public static void main(String[] args) throws IOException {
Person2 person = new Person2("Jessie", 35);
System.out.println("-- before serialization --");
System.out.println(person);
ObjectMapper om = new ObjectMapper();
String jsonString = om.writeValueAsString(person);
System.out.println("-- after serialization --");
System.out.println(jsonString);
}
} -- before serialization -- Person{name='Jessie', age=35} -- after serialization -- "Jessie - 35"
Example ProjectDependencies and Technologies Used: - jackson-databind 2.9.6: General data-binding functionality for Jackson: works on core streaming API.
- JDK 10
- Maven 3.5.4
|