杰克逊::在序列化中为对象添加额外的字段 [英] Jackson :: adding extra fields to an object in serialization

查看:367
本文介绍了杰克逊::在序列化中为对象添加额外的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在序列化为JSON时,我需要向对象添加新属性。属性的值是在运行时计算的,并且在对象中不存在。同样的对象也可以用于创建具有不同set ot字段的不同JSON(具有子类的基类,但我不想仅为JSON生成创建一个)。

I need to add new property to an object, when serializing to JSON. The value for the property is calculated on runtime and does not exist in the object. Also the same object can be used for creation of different JSON with different set ot fields (kind of having a base class with subclasses, but I don't want to create ones just for JSON generation).

这样做的最佳方法是什么,这不涉及创建自定义序列化程序类,它将负责整个对象字段的序列化?或者可以继承一些基本序列化程序,只需将其输出并以某种方式向其添加新字段?

What is the best way of doing that, which doesn't involve creation of custom serializer class, which will take care of serializing of whole set of object's fields? Or may be it is possible to inherit some "basic" serializer, and simply take it's output and add new field to it somehow?

我了解了混合,看起来可以重命名/隐藏某些字段,但似乎无法再添加一个字段。

I learned about mixins, and looks like it is possible to rename/hide some fields, however it seems not be possible to add an extra one.

推荐答案

你能不能只在价值类中添加一个方法?请注意,它不必是公共的,也不必使用getter命名约定;你可以这样做:

Can you not just add a method in value class? Note that it does not have to be either public, or use getter naming convention; you could do something like:

public class MyStuff {
   // ... the usual fields, getters and/or setters

   @JsonProperty("sum") // or whatever name you need in JSON
   private int calculateSumForJSON() {
        return 42; // calculate somehow
   }
}

否则你可以将POJO转换成JSON树值:

Otherwise you could convert POJO into JSON Tree value:

JsonNode tree = mapper.valueToTree(value);

然后通过添加属性等来修改它。

and then modify it by adding properties etc.

这篇关于杰克逊::在序列化中为对象添加额外的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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