1

jackson v1.9.13 spring 3.2.0 Hi, I've been spending days trying to figure out how to add a field into a JSON from a bean during serialization.

It seems like a very basic feature but I bumped into rubber walls every route I took.

What I want to achieve:

example bean:

package org.mydomain;

public class MyBean implements Serializable {
    private String foo;
    public void setFoo( String inValue ) {
        foo = inValue;
    }    
    public String getFoo() {
        return foo;
    }
}

output:

{
    "_type" : "org.mydomain.MyBean",
    "foo" : "bar"
}

I reckon that the simples way would be to extend a BeanSerializer write the "_type" property and delegate the super class serialization of the remaining fields. Problem is, the accessibility of methods and the "final" clause of some crucial methods makes it a quagmire.

I tried extending BeanSerializerBase, JsonSerializer, BeanSerializerModifier.

Every time I crash into some impenetrable 24-arguments-constructor or some non/mis-documented method.

Very frustrating.

Anyone has any idea on how to achieve the above bit?

I'm using spring-mvc, therefore I need a pluggable solution via ObjectMapper configuration. I don't want to pollute my model or controller objects with json specific annotation or serialization logic.

Thanks a lot.

N.

aekidna
  • 11
  • 3
  • 1
    Another way to achieve this is discussed in this question http://stackoverflow.com/questions/14714328/jackson-how-to-add-custom-property-to-the-json-without-modifying-the-pojo – Prashant C Chaturvedi Sep 17 '13 at 20:05

1 Answers1

-1

You can create a proxy class for MyBean and use it in place of MyBean. This doesn't require change in original class. You just need to replace the original MyBean object with proxy object. Although you can use without requiring an interface for MyBean but it's cleaner to use interface.

package org.mydomain;
public interface IMyBean{
    public String getFoo();
}
public class MyBean implements IMyBean,Serializable {
    private String foo;
    public void setFoo( String inValue ) {
        foo = inValue;
    }    
    public String getFoo() {
        return foo;
    }
}
public class MyBeanProxy implements IMyBean,Serializable {

    private IMyBean myBean;
    private String type;
    public MyBeanProxy(IMyBean myBean, String type){
        this.myBean = myBean;
        this.type = type;
    }

    public String getFoo() {
        return myBean.getFoo();
    }
    public String getType(){
        return type;
    }
}