如何使用Jackson有条件地序列化POJO的字段

rqdpfwrv  于 7个月前  发布在  其他
关注(0)|答案(3)|浏览(80)

我有一个java类

public class CategoryItem implements Serializable {
    private Long id;            

    private String name;           

    private Manager manager;
}

在一种情况下,我需要将所有字段转换为JSON。在另一种情况下,我只需要'id'和'name'我该怎么做?
给予点建议。谢谢

sczxawaw

sczxawaw1#

使用@JsonProperty注解POJO idname属性,使用@JsonIgnore注解管理器
如果只需要idname,请使用默认的ObjectMapper。当你需要所有的字段时,使用一个自定义的ObjectMapper。

6ljaweal

6ljaweal2#

有很多方法可以做到这一点:
1.将不需要的字段设置为null,并在类级别使用@JsonInclude(Include.NON_NULL)注解。
1.提供SimpleBeanPropertyFilter,同时使用ObjectMapper,并在类级别使用注解@JsonFilter(<filter_name>)
1.使用自定义序列化程序。

e0bqpujr

e0bqpujr3#

你可以用@JsonView来实现这一点(baeldung的荣誉):

@JsonView表示将包含属性以进行序列化/重新序列化的View。

例如,我们将使用@JsonView来序列化Item实体的示例。
首先,让我们从视图开始:

public class Views {
    public static class Public {}
    public static class Internal extends Public {}
}

下面是使用视图的Item实体:

public class Item {
    @JsonView(Views.Public.class)
    public int id;

    @JsonView(Views.Public.class)
    public String itemName;

    @JsonView(Views.Internal.class)
    public String ownerName;
}

最后是完整的测试:

@Test
public void whenSerializingUsingJsonView_thenCorrect()
  throws JsonProcessingException {
    Item item = new Item(2, "book", "John");

    String result = new ObjectMapper()
      .writerWithView(Views.Public.class)
      .writeValueAsString(item);

    assertThat(result, containsString("book"));
    assertThat(result, containsString("2"));
    assertThat(result, not(containsString("John")));
}

相关问题