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

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

serialized to the follow JSON:

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

请注意,age=25编码为number,而favoriteNumber=123编码为string.开箱即用的杰克逊将int封编组为一个数字.在本例中,我希望将favoriteNumber编码为字符串.

推荐答案

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应该为您处理从intInteger的自动装箱.

Json相关问答推荐

替换字符串中特殊字符的Jolt变换

JQ-JSON将键转换为对象

组合不同属性的Jolt Spec

规范化JSON数据

go 语言中的 JSON 到 XML

未知的META规范,无法验证.[规范v1.0.1]

JSONPath:查找子项目条件在字符串列表中的项目

将 JSON 文件放在哪里以在 Angular 8 应用程序中加载静态 JSON 数据?

在 json 嵌入的 YAML 文件中 - 使用 Python 仅替换 json 值

PowerShell - JSON/PsCustomObject - 为什么我的数组被扁平化为一个对象?

Swift - 将图像从 URL 写入本地文件

解析包含换行符的 JSON

从 HttpResponse 获取 json

C#扁平化json struct

alert Json 对象

有什么方法可以在 elasticsearch 服务器中导入 json 文件(包含 100 个文档).?

在自定义 JsonConverter 的 ReadJson 方法中处理空对象

使用 Retrofit 解析动态密钥 Json 字符串

使用 jQuery 和 JSON 填充表单?

如何使用 Powershell 将 JSON 对象保存到文件中?