-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,735
  • 3
  • 32
  • 56
D.Zhu
  • 9
  • 4

2 Answers2

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,735
  • 3
  • 32
  • 56
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,305
  • 4
  • 28
  • 44