Using Jackson JSON Views without annotating original bean class

后端 未结 1 2026
别那么骄傲
别那么骄傲 2020-12-28 22:44

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 c

相关标签:
1条回答
  • 2020-12-28 23:14

    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 {}
    
    0 讨论(0)
提交回复
热议问题