Custom BigInteger JSON serializer

不羁的心 提交于 2021-01-27 11:46:09

问题


I am trying to implement a custom JSON serializer class to display object BigInteger values as string in the JSON response.

I have implememented a custom serializer class

public class CustomCounterSerializer extends StdSerializer<BigInteger> {

    private static final long serialVersionUID = 5440920327083673598L;

    public CustomCounterSerializer() {
        this(BigInteger.class);
    }

    public CustomCounterSerializer(Class<BigInteger> vc) {
        super(vc);
    }

    @Override
    public void serialize(BigInteger value, JsonGenerator jsonGenerator, SerializerProvider provider) throws IOException {
        BigInteger valueJson = value==null ? BigInteger.valueOf(0) : value;
        jsonGenerator.writeString(valueJson.toString());
    }
}

The problem I have is that I want to handle the null object values using the overridden method and pass 0 to the JSON string and not null.

I have written a JUnit test for this:

public class CustomCounterSerializerTest {

    private ObjectMapper objectMapper = new ObjectMapper();

    @After
    public void tearDown() {
        objectMapper = null;
    }

    @Test
    public void testCustomSerializerWithNullValues() throws JsonParseException, JsonMappingException, IOException {
        MyObject obj = new MyObject();
        obj.setNonNullValue(BigInteger.valueOf(1);
        String obj_ = objectMapper.writeValueAsString(obj);
        assertThat(obj_).isNotNull();
        assertTrue(obj_.contains("\"nonNullValue\":\"" + BigInteger.valueOf(1).toString() + "\",\"nullValue\":\""+ BigInteger.valueOf(0).toString() +"\""));
    }

}

It fails as it contains null and not nullValue:"0".

But the null value of the object always goes to no args constructor and even like this(BigInteger.class) does not use my method and prints null.


回答1:


You need to tell Jackson that it should use your serializer even for null values. You do this by using @JsonSerializer also with the nullsUsing parameter.

In your MyObject class it would look like this:

@JsonSerialize(using = CustomCounterSerializer.class,
               nullsUsing = CustomCounterSerializer.class)
private BigInteger nullValue;


来源:https://stackoverflow.com/questions/53647390/custom-biginteger-json-serializer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!