简体   繁体   English

Jackson-用于对象内部属性的自定义序列化器

[英]Jackson - Custom serializer for propeties inside object

I'm looking for a way to output all BigIntegers as string using Jackson. 我正在寻找一种使用Jackson将所有BigIntegers输出为字符串的方法。 These BigIntegers are used in many classes all over my app, so adding @JsonSerialize to all fields is not an option. 这些BigIntegers在我的应用程序的许多类中都使用过,因此,在所有字段中添加@JsonSerialize不是一种选择。

I have created a custom Jackson serializer, but this only works on the base class, being serialized, not the properties inside the class. 我创建了一个自定义的Jackson序列化程序,但这仅适用于被序列化的基类,而不适用于该类内部的属性。 So, this does not work: 因此,这不起作用:

public class BigIntegerSerializer extends JsonSerializer<BigInteger> {

    @Override
    public void serialize(BigInteger value, JsonGenerator jgen,
                      SerializerProvider provider) throws IOException {
        jgen.writeString(value + "");
    }
}

Is there a way to have a Jackson serialized on all properties of a certain type, without adding @JsonSerialize to all? 有没有一种方法可以让Jackson在某种类型的所有属性上序列化,而不必对所有属性都添加@JsonSerialize?

The object to be serialized can be any POJO containing BigIntegers. 要序列化的对象可以是任何包含BigIntegers的POJO。

PS: The idea to convert BigIntegers to String is so that JavaScript will not convert these numbers to scientific notation. PS:将BigIntegers转换为String的想法是让JavaScript不会将这些数字转换为科学计数法。 All my primary keys use BigInteger, so when JavaScript converts them to scientific notation, I can not longer use them. 我所有的主键都使用BigInteger,因此当JavaScript将其转换为科学计数法时,我将无法再使用它们。

Take a look at this guide . 看一下本指南 For example 例如

ObjectMapper mapper = new ObjectMapper();
SimpleModule testModule = new SimpleModule("MyModule", new Version(1, 0, 0, null));
testModule.addSerializer(new BigIntegerSerializer());
mapper.registerModule(testModule);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM