自定义BigInteger JSON序列化器 [英] Custom BigInteger JSON serializer

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

问题描述

我正在尝试实现一个自定义JSON序列化器类,以将对象BigInteger的值显示为JSON响应中的字符串.

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

我遇到的问题是我想使用重写的方法处理null对象的值,并将0传递给JSON字符串而不是null.

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.

我为此编写了一个JUnit测试:

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

}

它失败,因为它包含null而不是nullValue:"0".

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

但是对象的null值始终不使用args构造函数,甚至像this(BigInteger.class)都不使用我的方法并显示null一样.

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.

推荐答案

您需要告诉Jackson,它应该使用序列化程序 即使是空值.您可以通过使用@JsonSerializer 还可以使用 nullsUsing 参数.

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.

在MyObject类中,它看起来像这样:

In your MyObject class it would look like this:

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

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

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