Salomon BRYS
Salomon BRYS

Reputation: 9584

jackson serializer: get serialized object

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 :

or

I used to do that all the time with GSon but Jackson provides loads of feature that I would love to use ;)

Upvotes: 0

Views: 465

Answers (1)

Geert-Jan
Geert-Jan

Reputation: 18895

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

Upvotes: 0

Related Questions