java - How to exclude in JSON property of an object (inside output class)? -
let's have piece of code output class used json:
studentsummary.java public class studentsummary { studentlist studentlist; //getters setters }
and studentlist
studentlist.java public class studentlist { int numberofstudents; int totalexpenditures; list<student> students; //getters setters }
after making service call, json output:
{ "studentsummary": { "studentlist": { "numberofstudents": 500 "totalexpenditures": 250000 "students": [ { //students listed } ] } }
what want do, exclude json students list in studentsummary output class, looks this:
{ "studentsummary": { "studentlist": { "numberofstudents": 500 "totalexpenditures": 250000 } }
i've tried using (in studentsummary output class) @jsonignore
, @jsonproperties
, specifying exclude "studentlist.students"
, doesn't anything.
edit: further clarification, why couldn't changes inside studentlist class, it's because used service , service studentsummary class of different service, can make changes inside latter class, without modifying previous service.
summary
this solve problem:
public class studentsummary { @jsonignoreproperties(value = { "students" }) public studentlist studentlist = new studentlist();
you not need edit studentlist
class.
all test class definitions
student
public class student { string name = "student" + math.random()*100; public string getname() { return name; } public void setname(string name) { this.name = name; } }
studentlist
public class studentlist { int numberofstudents; int totalexpenditures; list<student> students = new arraylist<>(); public studentlist(){ for(int =0; i<10; i++){ students.add(new student()); } } public int getnumberofstudents() { return numberofstudents; } public void setnumberofstudents(int numberofstudents) { this.numberofstudents = numberofstudents; } public int gettotalexpenditures() { return totalexpenditures; } public void settotalexpenditures(int totalexpenditures) { this.totalexpenditures = totalexpenditures; } public list<student> getstudents() { return students; } public void setstudents(list<student> students) { this.students = students; } //getters setters }
studentsummary
public class studentsummary { @jsonignoreproperties(value = { "students" }) public studentlist studentlist = new studentlist(); public studentsummary(){ studentlist = new studentlist(); } public studentlist getstudentlist() { return studentlist; } public void setstudentlist(studentlist studentlist) { this.studentlist = studentlist; } //getters setters }
main class
objectmapper mapper = new objectmapper(); studentsummary summary = new studentsummary(); string test = mapper.writevalueasstring(summary); system.out.println(test); system.out.print("done");
Comments
Post a Comment