Using Jackson JSON Views without annotating the original bean class

Is there a way I can use Jackson JSON Views or something like that without having to comment on the original bean class? I am looking for some kind of runtime / dynamic configuration to allow me to do something like this.

My bean is an @Entity packaged in a JAR that can be used by several projects. I try to avoid touching and repackaging the common JAR due to user interface changes in consuming projects.

Ideally, I would like to do something like

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

to replace

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

Any ideas?

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

+8
json spring jackson spring-mvc
source share
1 answer

How to use the mix-in function?

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 {} 
+12
source share

All Articles