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.

4

1 回答 1

-1

您可以创建一个代理类MyBean并使用它来代替MyBean. 这不需要更改原始课程。您只需要将原始MyBean对象替换为代理对象。尽管您可以在不需要接口的情况下使用,MyBean但使用接口更清洁。

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;
    }
}
于 2013-09-17T19:50:32.960 回答