2013-07-26 34 views
1

jackson v1.9.13 spring 3.2.0 嗨, 我一直在花费数天的时间试图找出如何在序列化期间从bean中将字段添加到JSON中。Spring-MVC Jackson。豆序列化期间添加字段

这似乎是一个非常基本的功能,但我碰到橡胶墙,我走的每条路线。

我想达到的目标:

例如豆:

package org.mydomain; 

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

输出:

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

我估计simples的方法是延长BeanSerializer写“_type”属性并委派剩余字段的超类序列化。问题是,方法的可访问性和一些关键方法的“最终”条款使其成为泥潭。

我试着扩展BeanSerializerBase,JsonSerializer,BeanSerializerModifier。

每次我碰到一些不可穿透的24个参数的构造函数或者一些没有错误记录的方法时。

非常令人沮丧。

任何人有任何想法如何实现上述位?

我使用spring-mvc,因此我需要通过ObjectMapper配置的可插拔解决方案。我不想用json特定的注释或序列化逻辑来污染模型或控制器对象。

非常感谢。

N.

+1

另一种方式来实现这一目标在这个问题上http://stackoverflow.com/questions/14714328/jackson-how-to-add-custom-property-to-the-json-without-modifying-讨论该POJO的 –

回答

-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; 
    } 
} 
相关问题