0

I have a problem with Serializer, here is my problem :

I have a bean class like that :

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

When Serializing through Jackson, without the @ JsonSerialize annotation, I obviously get :

{ "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...

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.

So the question can be :

  • How, from inside a JsonSerializer can I serialize the object without re-calling the serializer itself ?

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 ;)

Salomon BRYS
  • 9,247
  • 5
  • 29
  • 44

1 Answers1

0

I'm pretty sure a getter, in your example getVersion(), without a backing property would suffice, in which you'd generate 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

Geert-Jan
  • 18,623
  • 16
  • 75
  • 137