使用Jackson JSON Views而不注释原始bean类 [英] Using Jackson JSON Views without annotating original bean class

查看:194
本文介绍了使用Jackson JSON Views而不注释原始bean类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is there any way that I can use Jackson JSON Views or something like it, without having to annotate the original bean class? I'm looking for some kind of runtime/dynamic configuration to let me do something similar.

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

My bean is an @Entity packaged in a JAR that may be shared by multiple projects. I'm trying to avoid touching and re-packaging the shared JAR because of UI changes in the consuming projects.

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

Ideally I'd like to do something like

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。

Underlying environment: Spring 3.0, Spring MVC and Glassfish 3.1.1.

推荐答案

如何使用Mix-In功能?

How about using the Mix-In feature?

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 {}

这篇关于使用Jackson JSON Views而不注释原始bean类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆