簡體   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