【问题标题】:Using Jackson JSON Views without annotating original bean class使用 Jackson JSON 视图而不注释原始 bean 类
【发布时间】:2012-01-18 13:05:06
【问题描述】:

有没有什么方法可以使用 Jackson JSON Views 或类似的东西,而不必注释原始 bean 类?我正在寻找某种运行时/动态配置来让我做类似的事情。

我的 bean 是一个 @Entity 打包在一个 JAR 中,可以由多个项目共享。由于消费项目中的 UI 更改,我试图避免触摸和重新打包共享 JAR。

理想情况下,我想做类似的事情

jsonViewBuilder = createViewBuilder(View.class);
jsonViewBuilder.addProperty("property1");
jsonViewBuilder.addProperty("property2");

替换

Bean {
  @JsonView(View.class)
  String property1;

  @JsonView(View.class)
  String property2;
}

有什么想法吗?

底层环境:Spring 3.0、Spring MVC 和 Glassfish 3.1.1。

【问题讨论】:

    标签: json spring spring-mvc jackson


    【解决方案1】:

    使用混音功能怎么样?

    http://wiki.fasterxml.com/JacksonMixInAnnotations

    http://www.cowtowncoder.com/blog/archives/2009/08/entry_305.html


    import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
    import org.codehaus.jackson.annotate.JsonMethod;
    import org.codehaus.jackson.map.ObjectMapper;
    import org.codehaus.jackson.map.SerializationConfig;
    import org.codehaus.jackson.map.annotate.JsonView;
    
    public class JacksonFoo
    {
      public static void main(String[] args) throws Exception
      {
        ObjectMapper mapper = new ObjectMapper().setVisibility(JsonMethod.FIELD, Visibility.ANY)
            .configure(SerializationConfig.Feature.DEFAULT_VIEW_INCLUSION, false);
        mapper.getSerializationConfig().addMixInAnnotations(Bar.class, BarMixIn.class);
        mapper.setSerializationConfig(mapper.getSerializationConfig().withView(Expose.class));
    
        System.out.println(mapper.writeValueAsString(new Bar()));
        // output: {"b":"B"}
      }
    }
    
    class Bar
    {
      String a = "A";
      String b = "B";
    }
    
    abstract class BarMixIn
    {
      @JsonView(Expose.class)
      String b;
    }
    
    // Used only as JsonView marker.  
    // Could use any existing class, like Object, instead.  
    class Expose {}
    

    【讨论】:

    • 我可以在@JsonView 中使用mixin 注释吗?示例仅显示@JsonProperty。
    • 是的。用示例更新了答案。
    • 效果很好,谢谢!现在,如果只有一种方法可以重构该设置以避免在每个控制器中重复。
    • 应该可以给 Spring 一个完全配置的 ObjectMapper 实例,希望其他人可以分享这样的设置(我看过基于 xml config 的):但我看过的一篇文章是这样的:hillert.blogspot.com/2011/01/…
    猜你喜欢
    • 2011-06-22
    • 2016-06-13
    • 2011-12-20
    • 2016-03-09
    • 2020-01-03
    • 1970-01-01
    • 1970-01-01
    • 2021-05-09
    • 1970-01-01
    相关资源
    最近更新 更多