Jackson JSON针对某些领域的自定义序列化 [英] Jackson JSON custom serialization for certain fields

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

问题描述

有没有办法使用Jackson JSON处理器进行自定义字段级序列化?例如,我想要类

Is there a way using Jackson JSON Processor to do custom field level serialization? For example, I'd like to have the class

public class Person {
    public String name;
    public int age;
    public int favoriteNumber;
}

序列化为以下JSON:

serialized to the follow JSON:

{ "name": "Joe", "age": 25, "favoriteNumber": "123" }

请注意,age = 25编码为数字,而favoriteNumber = 123编码为字符串。开箱即用杰克逊marshalls int 到一个数字。在这种情况下,我希望favoriteNumber被编码为字符串。

Note that age=25 is encoded as a number while favoriteNumber=123 is encoded as a string. Out of the box Jackson marshalls int to a number. In this case I want favoriteNumber to be encoded as a string.

推荐答案

您可以按如下方式实现自定义序列化程序:

You can implement a custom serializer as follows:

public class Person {
    public String name;
    public int age;
    @JsonSerialize(using = IntToStringSerializer.class, as=String.class)
    public int favoriteNumber:
}


public class IntToStringSerializer extends JsonSerializer<Integer> {

    @Override
    public void serialize(Integer tmpInt, 
                          JsonGenerator jsonGenerator, 
                          SerializerProvider serializerProvider) 
                          throws IOException, JsonProcessingException {
        jsonGenerator.writeObject(tmpInt.toString());
    }
}

Java应该从 int 到整数为你。

Java should handle the autoboxing from int to Integer for you.

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

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