简体   繁体   English

杰克逊序列化器:获取序列化的对象

[英]jackson serializer: get serialized object

I have a problem with Serializer, here is my problem : 我的序列化器有问题,这是我的问题:

I have a bean class like that : 我有一个像这样的bean类:

@JsonSerialize(using = MyObjectSerializer.class)
public class MyObject {
    public int a;
    public boolean b;
}

When Serializing through Jackson, without the @ JsonSerialize annotation, I obviously get : 通过杰克逊进行序列化时,如果没有@ JsonSerialize批注,我显然会得到:

{ "a": 42, "b": true}

But I need to add a property so it gives : 但是我需要添加一个属性,以便提供:

{ "a": 42, "b": true, "version": "0.1-beta" }

(This is an example, in the real world, the property I add depends on several properties of the object) (这是一个示例,在现实世界中,我添加的属性取决于对象的多个属性)

So I need to write a custom serializer. 因此,我需要编写一个自定义的序列化程序。 However, in my real code, the class contains much more properties than just 2. So I don't want to manually create those properties to the json object... 但是,在我的真实代码中,该类包含的属性远远不止2个。因此,我不想手动为json对象创建这些属性...

If I use this : 如果我使用这个:

public static class MyObjectSerializer extends JsonSerializer<MyObject> {
    @Override public void serialize(MyObject obj, JsonGenerator json, SerializerProvider provider) throws IOException, JsonProcessingException {
        json.writeObject(obj);
    }
}

I obviously get a StackOverflowError. 我显然得到一个StackOverflowError。

So the question can be : 因此问题可能是:

  • How, from inside a JsonSerializer can I serialize the object without re-calling the serializer itself ? 我如何在JsonSerializer内部对对象进行序列化而无需重新调用序列化器本身?

or 要么

  • How can I dynamically add properties to an object beeing serialized. 如何动态地将属性添加到已序列化的对象。

I used to do that all the time with GSon but Jackson provides loads of feature that I would love to use ;) 我过去一直使用GSon来做到这一点,但杰克逊提供了很多我想使用的功能;)

I'm pretty sure a getter, in your example getVersion() , without a backing property would suffice, in which you'd generate 0.1-beta . 我敢肯定,在您的示例getVersion() ,没有后备属性的吸气剂就足够了,在其中可以生成0.1-beta (or generate the value based on the values of a couple of properties as you describe). (或根据您描述的几个属性的值生成值)。

So no need for a custom serializer just for this purpose 因此,不需要为此专门定制的序列化程序

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM