@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
Use the annotation
@JsonIgnore
on the fields which you do not want to be serialized.More info on the annotation @JsonIgnore.
You can set the ObjectMapper to not include fields that return a null value in the JSON.