某些字段的 Jackson JSON 自定义序列化 [英] Jackson JSON custom serialization for certain fields
问题描述
有没有办法使用 Jackson JSON Processor 进行自定义字段级序列化?例如,我想上课
Is there a way using Jackson JSON Processor to do custom field level serialization? For example, I'd like to have the class
public class Person {
public String name;
public int age;
public int favoriteNumber;
}
序列化为以下 JSON:
serialized to the follow JSON:
{ "name": "Joe", "age": 25, "favoriteNumber": "123" }
请注意,age=25 被编码为数字,而 favoriteNumber=123 被编码为字符串.开箱即用的 Jackson 将 int
编组为一个数字.在这种情况下,我希望将 favoriteNumber 编码为字符串.
Note that age=25 is encoded as a number while favoriteNumber=123 is encoded as a string. Out of the box Jackson marshalls int
to a number. In this case I want favoriteNumber to be encoded as a string.
推荐答案
您可以按如下方式实现自定义序列化器:
You can implement a custom serializer as follows:
public class Person {
public String name;
public int age;
@JsonSerialize(using = IntToStringSerializer.class, as=String.class)
public int favoriteNumber:
}
public class IntToStringSerializer extends JsonSerializer<Integer> {
@Override
public void serialize(Integer tmpInt,
JsonGenerator jsonGenerator,
SerializerProvider serializerProvider)
throws IOException, JsonProcessingException {
jsonGenerator.writeObject(tmpInt.toString());
}
}
Java 应该为您处理从 int
到 Integer
的自动装箱.
Java should handle the autoboxing from int
to Integer
for you.
这篇关于某些字段的 Jackson JSON 自定义序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!