-1

I have a java class

    public class CategoryItem implements Serializable {
    private Long id;            

    private String name;           

    private Manager manager;
}

In one case,I need to convert all the fields to json. on the other case,I only need 'id'and 'name' How can I do?

Give me some tips.Thanks

Catchwa
  • 5,845
  • 4
  • 31
  • 57
D.Zhu
  • 9
  • 4

3 Answers3

0

Annotate your POJO id and name attributes with @JsonProperty and manager with @JsonIgnore

When you want just id and name, use a default ObjectMapper. When you want all fields, use a custom ObjectMapper per this question/answer.

Catchwa
  • 5,845
  • 4
  • 31
  • 57
0

There are many ways to do this:

  1. set unwanted field to null, and use @JsonInclude(Include.NON_NULL) annotation at class level.

  2. supply SimpleBeanPropertyFilter, while using ObjectMapper and use annotation @JsonFilter(<filter_name>) at class level.

  3. use a custom-serializer.

Sachin Gupta
  • 7,805
  • 4
  • 30
  • 45
0

You can achieve this with @JsonView (kudos to baeldung):

@JsonView indicates the View in which the property will be included for serialization/deserialization.

For example, we'll use @JsonView to serialize an instance of Item entity.

First, let's start with the views:

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

Next here's the Item entity using the views:

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

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

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

Finally, the full test:

@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")));
}
Tob
  • 352
  • 2
  • 8