除了其他答案外,@JsonProperty
如果您@JsonCreator
在没有no-arg构造函数的类中使用注释,则注释确实非常重要。
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);
}
}
在此示例中,唯一的构造函数被标记为@JsonCreator
,因此Jackson将使用该构造函数创建实例。但是输出是这样的:
序列化:{“ stringValue”:“ ABCD”,“ myEnum”:“ FIRST”}
线程“主”中的异常com.fasterxml.jackson.databind.exc.InvalidFormatException:无法从字符串值'stringValue'构造ClassToSerialize $ MyEnum实例
:值不是声明的Enum实例名称之一:[FIRST,SECOND,THIRD]
但是在@JsonProperty
构造函数中添加注释后:
@JsonCreator
public ClassToSerialize(@JsonProperty("myEnum") MyEnum myEnum) {
this.myEnum = myEnum;
}
反序列化成功:
序列化:{“ myEnum”:“ FIRST”,“ stringValue”:“ ABCD”}
字符串值:ABCD
MyEnum:第一