skip to Main Content
 @JsonPropertyOrder({
     "aaaa",
     "bbb",
     "cccc"
     })

 public class myDto {
 
     @Id
     private String id;
 
     @Valid
     @NotNull
     @JsonProperty("aaaa")
     private String aaaa;
 
     @Valid
     @NotNull
     @JsonProperty("bbbb")
     private List<String> bbbb;
 
     @Valid
     @NotNull
     @JsonProperty("cccc")
     private List<String> cccc;
 
    // getter and setter for above 4
 }

I want to convert it to JSON to include field aaaa, bbbb, ccc only.
Expected output: {"aaaa":"1","bbbb":["1"],"cccc":["1"]}

I tried to create JSON using following but it included ID field, meta, link fields as well.

 String test = objectMapper.writeValueAsString(myDto); 
 configuration = new JSONObject(test);

Output: {"aaaa":"1","bbbb":["1"],"cccc":["1"],"meta":null,"links":null,"id":null}

Expected output: {"aaaa":"1","bbbb":["1"],"cccc":["1"]}

2

Answers


  1. Use the annotation @JsonIgnore on the fields which you do not want to be serialized.

     public class myDto {
    
         @Id
         @JsonIgnore
         private String id;
    

    More info on the annotation @JsonIgnore.

    Login or Signup to reply.
  2. You can set the ObjectMapper to not include fields that return a null value in the JSON.

    objectMapper.setSerializationInclusion(Include.NON_NULL)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search