As addition to other answers, @JsonProperty
annotation is really important if you use the @JsonCreator
annotation in classes which do not have a no-arg constructor.
public class ClassToSerialize {
public enum MyEnum {
FIRST,SECOND,THIRD
}
public String stringValue = "ABCD";
public MyEnum myEnum;
@JsonCreator
public ClassToSerialize(MyEnum myEnum) {
this.myEnum = myEnum;
}
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
ClassToSerialize classToSerialize = new ClassToSerialize(MyEnum.FIRST);
String jsonString = mapper.writeValueAsString(classToSerialize);
System.out.println(jsonString);
ClassToSerialize deserialized = mapper.readValue(jsonString, ClassToSerialize.class);
System.out.println("StringValue: " + deserialized.stringValue);
System.out.println("MyEnum: " + deserialized.myEnum);
}
}
In this example the only constructor is marked as @JsonCreator
, therefore Jackson will use this constructor to create the instance. But the output is like:
Serialized: {"stringValue":"ABCD","myEnum":"FIRST"}
Exception in thread "main" com.fasterxml.jackson.databind.exc.InvalidFormatException: Can not construct instance of ClassToSerialize$MyEnum from String value 'stringValue': value not one of declared Enum instance names: [FIRST, SECOND, THIRD]
But after the addition of the @JsonProperty
annotation in the constructor:
@JsonCreator
public ClassToSerialize(@JsonProperty("myEnum") MyEnum myEnum) {
this.myEnum = myEnum;
}
The deserialization is successful:
Serialized: {"myEnum":"FIRST","stringValue":"ABCD"}
StringValue: ABCD
MyEnum: FIRST