简体   繁体   中英

Jackson - Custom serializer for propeties inside object

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.

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 + "");
    }
}

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

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

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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