Jackson dynamic property names

I had a simpler solution using @JsonAnyGetter annotation, and it worked like a charm.

import java.util.Collections;
import java.util.Map;

public class Response {
    private Status status;
    private String error;

    @JsonIgnore
    private Object data;

    [getters, setters]

    @JsonAnyGetter
    public Map<String, Object> any() {
        //add the custom name here
        //use full HashMap if you need more than one property
        return Collections.singletonMap(data.getClass().getName(), data);
    }
}

No wrapper needed, no custom serializer needed.

Leave a Comment