Json and Java - Circular Link

I have a problem with the Circular link.

I have Rest Webservices that returns objects to the front, the problem is that I'm trying to return objects that have multiple links, so that as a result I get an endless response that generates

java.lang.IllegalStateException: Cannot call sendError() after the response has been committed 

Objects are automatically generated using Hibernate Code Generation, and I need to have a circular link in the backend, I just need to delete it before sending the information to the external interface using Jackson.

Controller Header:

 @RequestMapping(value="/list", method=RequestMethod.POST) public @ResponseBody eventResponse list(@RequestBody String sessionID) { 

I am not doing anything to convert to Json, I am new to this and I think Jackson solved this automatically.

+11
java json jackson circular-reference
Jun 30 '13 at 19:00
source share
2 answers

There are two ways around this. If you must expose your entity to the outside world, I recommend adding @JsonIgnore to the property that calls the circular reference. This will tell Jackson not to serialize this property.

Another way is to use the bidirectional functions provided by Jackson. You can use @JsonManagedReference or @JsonBackReference . @JsonManagedReference is the "forward" part of the property, and it will be serialized as usual. @JsonBackReference is the "back" part of the link; it will not be serialized, but will be restored when the forward descriptor is deserialized.

You can check examples here .

Your comment is expressed in this: I think that in this case you can make use of the DTO visible to the outside world. I like this approach because I do not want to reveal my entities outside. This means that Jackson's annotations will be on the DTO, not on enity. You will need some kind of cartographer or converter that converts the entity to DTO. Now, when you make changes to your entity, they will not be distributed in the DTO unless you change your converter / converter. I think this is normal, because when you make changes to your essence, you can decide whether you want this change to be open or not.

UPDATE

There is a good blog post here that details the various ways to handle bidirectional relationships in Jackson. It describes solutions that use @JsonIgnore , @JsonManagedReference and @JsonBackReference , @JsonIdentityInfo , @JsonView and its own serializer. This is a fairly complete record of the various methods you can use.

+23
Jun 30 '13 at 19:03
source share

The only annotation @JsonIdentityInfo solves the problem. It also handles circular links. Link

+5
Oct 21 '15 at 13:21
source share



All Articles