I am creating a json body using jackson in java. It will be something like below
{
"subject": "math",
"marks": "100",
"student":{
"name": "x",
"class": "8"
}
}
Based on different REST URIs, the json body should ignore some fields or elements. How to ignore a part of the “student” from the above json body using jackson? When I ignore it, I can only get
{ "subject": "math", "marks": "100"}
but I get it as below, which is wrong -
{ "subject": "math", "marks": "100","student":{}}
I have two classes with getters and setters, one of which is the subject, and the other is the student. I tried using @JsonIgnore, but it ignores all URIs that I don't want. I also tried @JsonInclude (Include.NON_EMPTY). How to achieve this?
. REST URI json . , URI , . = ();
score.setSubject("math");
score.setMarks("100");
Score.Student student =score.new Student();
score.setStudent(student);
switch (type) {
case StudentAdd:
score.setSubject("math");
score.setMarks("100");
break;
case StudentDelete:
score.setSubject("math");
score.setMarks("100");
break;
case StudentComplete:
score.setChangeReason("C");
default:
break;
score.setSubject("math");
score.setMarks("100");
score.setStudent(student);
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
objectMapper.setSerializationInclusion(Include.NON_EMPTY);
StringWriter jsonBody = new StringWriter();
objectMapper.writeValue(jsonBody, score);
return jsonBody.toString();
}
class Score {
private String subject;
private String marks;
private Student student;
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getMarks() {
return marks;
}
public void setMarks(String marks) {
this.marks = marks;
}
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
class Student {
private String name;
@JsonProperty("class")
private String clazz;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getClazz() {
return clazz;
}
public void setClazz(String clazz) {
this.clazz = clazz;
}
}
}
}
}