如何在Jackson的json序列化过程中向对象添加额外的字段? [英] How to add extra fields to an Object during Jackson's json serialization?

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

问题描述

当序列化为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?

我了解了 mixins ,并且看起来可以重命名/隐藏某些字段,但是似乎无法添加一个额外的.

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.

这篇关于如何在Jackson的json序列化过程中向对象添加额外的字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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