Best way to avoid sleeping lazy init exception when serializing in json response

This is a link to a question I asked a month ago .

In this question, the answer is to avoid the lazy init exception when json serialization was to set null to variables that cause the lazy initialization exception. But consider when a class has many dependencies. Now that the code base is growing, and every time I have to set zero for problem variables everywhere in the code, to avoid the json serialization problem. The method does not look neat when the code base is large.

Below is an example of code that doesn't look very good.

//setting some variables to avoid lazy init exception in jackson mapper serialization batch.setEnrollmentList(null); List<BatchSchedule> scheduleList = (ArrayList<BatchSchedule>) batch.getBatchScheduleList(); for (BatchSchedule batchSchedule : scheduleList) { batchSchedule.setBatch(null); } batch.getLecturer().setBatchList(null); batch.getLecturer().setSubjectList(null); batch.getSubject().setBatchList(null); batch.getSubject().setLecturerList(null); 

Could you suggest me the best way to deal with this problem. Thanks.

+6
source share
1 answer

You can annotate lazy properties with @JsonIgnore so Jackson ignores it when serializing.

+4
source

All Articles