Jackson-用于对象内部属性的自定义序列化器 [英] Jackson - Custom serializer for propeties inside object

查看:74
本文介绍了Jackson-用于对象内部属性的自定义序列化器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种使用Jackson将所有BigIntegers输出为字符串的方法.这些BigIntegers在我的应用程序的许多类中都使用过,因此不能在所有字段中添加@JsonSerialize.

I'm looking for a way to output all BigIntegers as string using Jackson. These BigIntegers are used in many classes all over my app, so adding @JsonSerialize to all fields is not an option.

我已经创建了一个自定义的Jackson序列化程序,但这仅适用于被序列化的基类,而不适用于该类内部的属性.因此,这不起作用:

I have created a custom Jackson serializer, but this only works on the base class, being serialized, not the properties inside the class. 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 + "");
    }
}

有没有一种方法可以让Jackson对某种类型的所有属性进行序列化,而不必对所有属性都添加@JsonSerialize?

Is there a way to have a Jackson serialized on all properties of a certain type, without adding @JsonSerialize to all?

要序列化的对象可以是任何包含BigIntegers的POJO.

The object to be serialized can be any POJO containing BigIntegers.

PS:将BigIntegers转换为String的想法是让JavaScript不会将这些数字转换为科学计数法.我所有的主键都使用BigInteger,因此当JavaScript将它们转换为科学计数法时,我将无法再使用它们.

PS: The idea to convert BigIntegers to String is so that JavaScript will not convert these numbers to scientific notation. All my primary keys use BigInteger, so when JavaScript converts them to scientific notation, I can not longer use them.

推荐答案

看看本指南 .例如

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

这篇关于Jackson-用于对象内部属性的自定义序列化器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆