繁体   English   中英

使用JsonView Jackson的Json序列化

[英]Json Serialization with JsonView Jackson

我有一个类,我想序列化忽略一些属性

public class User extends Model
{
    static class publicView{}

    @JsonView(publicView.class)
    private Long id;

    private String showName;

    @JsonView(publicView.class)
    private List<qQueue> callableQueues;

}

当我在没有JsonView的情况下进行序列化时,我通常会做这样的事情

public JsonNode jsonSerialization()
{
    ObjectMapper mapper = new ObjectMapper();
    return mapper.convertValue(this, JsonNode.class);  
}

如何使用“publicView”类进行序列化?

您可以配置对象映射器以包含publicView.class并排除其他字段,如下所示:

  • 禁用MapperFeature.DEFAULT_VIEW_INCLUSION映射器功能。
  • 通过ObjectMapper#getSerializationConfig().withView()方法启用序列化视图。

请参阅此页面以供参考。

这是一个例子:

public class JacksonView1 {
    public static class publicView{}

    public static class User  {
        public User(Long id, String showName, List<String> callableQueues) {
            this.id = id;
            this.showName = showName;
            this.callableQueues = callableQueues;
        }
        @JsonView(publicView.class)
        public final Long id;

        public final String showName;

        @JsonView(publicView.class)
        public final List<String> callableQueues;
    }

    public static void main(String[] args) {
        User user = new User(123l, "name", Arrays.asList("a", "b"));
        ObjectMapper mapper = new ObjectMapper();
        mapper.disable(MapperFeature.DEFAULT_VIEW_INCLUSION);
        mapper.setConfig(mapper.getSerializationConfig()
                .withView(publicView.class));
        System.out.println(mapper.convertValue(user, JsonNode.class));
    }
}

输出:

{"id":123,"callableQueues":["a","b"]}

感谢Alexey Gavrilov,我找到了一个解决方案,它可能不是最合适的但是有效。

public JsonNode jsonSerialization()
{
    ObjectMapper mapper = new ObjectMapper();
    try 
    {
        mapper.disable(MapperFeature.DEFAULT_VIEW_INCLUSION);
        return Json.parse(mapper.writerWithView(publicView.class).writeValueAsString(this));
    } 
    catch (JsonProcessingException ex) 
    {
        return null;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM