Getting JSON from Jersey with circular dependencies

。_饼干妹妹 提交于 2019-12-11 00:34:03

问题


I am writing a service that uses Jersey and JAXB. My classes are annotated with @XMLRootElement, @XMLElement, etc. I have a circular dependency between two classes, so I have annotated the circular dependent property with @XMLTransient. So when I call my service I get xml as the default, which works perfectly. However, when I try using JSON, I get repeated lines like:

{"name":"dere","entries":[{"points":0,"wins":0,"losses":0,"ties":0,"leaderboard":{"name":"dere","entries":[{"points":0,"wins":0,"losses":0,"ties":0,"leaderboard":{"name":"dere","entries":[{"points":0,"wins":0,"losses":0,"ties":0,"leaderboard":{"name":"dere","entries":[{"points":0,"wins":0,"losses":0,"ties":0,"leaderboard":{"name":"dere"," ... etc.

So it seems there is a problem with circular dependencies when I am using JSON. I would like to avoid the circular dependent item from showing up in the JSON output, like it is done in XML (because of the @XMLTransient annotation).

Can anyone provide any insight on how I would be able to achieve this?


回答1:


Use @JsonIgnore instead of @XmlTransient to break the circular dependency.

I had a similar problem as you and this did the trick for me.




回答2:


It's probably worth checking out Kris Zyp's JSON Referencing proposal. It was invented specifically to handle multiple references and circular references in JSON data.

(Note: Despite the article title, Dojo isn't required. The original proposal was on json.com, but that site is inaccessible to me at the moment.)

How you would implement this technique in Jersey is, unfortunately, an exercise left to the reader.



来源:https://stackoverflow.com/questions/1434931/getting-json-from-jersey-with-circular-dependencies

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!