JAXB A cycle is detected in the object graph

倾然丶 夕夏残阳落幕 提交于 2020-03-11 13:17:06

问题


I want to convert my pojo to json with JAXB, my pojo have one to many relation, and when i convert my pojo to json, JAXB generate error "A cycle is detected in the object graph. This will cause infinitely deep XML".

I read from web that, this problem can be solved with help from @XmlID and @XmlIDREF, but there is one problem, my Id attribute is not String type but Long. and as far as i know @XmlID can be used only with String property.

Other web suggest using eclipselink MOXy, but MOXy cannot generate json.


回答1:


As you mentioned in your question EclipseLink MOXy (I'm the tech lead) has the @XmlInverseReference annotation to solve the problem of bidirectional relationships. As of EclipseLink 2.4 MOXy can produce/consume JSON.

For More Information

  • http://bdoughan.blogspot.com/2010/07/jpa-entities-to-xml-bidirectional.html
  • http://blog.bdoughan.com/2011/08/json-binding-with-eclipselink-moxy.html



回答2:


You have a cyclic reference problem in your definition.

Try putting @XmlTransient above the problematic definition.

Also, about XmlID and string type, see http://markmail.org/message/up6vrzjixxrvy5th.




回答3:


The JAXB specification requires that the property marked with @XmlID be a String property. MOXy impl allows to use long.

One hack to keep using full JAXB compliant implementation would be to duplicate your id in a String field (before serialising)

Don't know so much about JAXB but XStream makes you able to use different modes and some of these modes will give references to the xpath address (absolute or relative) of an element in your xml, if these elements are already displayed. (And you can do Json with XStream)




回答4:


I faced similar problem when I wanted to convert my POJO to JSON with JaxRS. The MoxyJsonProvider is the default option of eclipselink but it fails to parse the JSOG (where cycles exists in the JSON structure). Jackson Jaxb Provider does this better with ObjectMapper.

I have elaborated in this answer below, about how to invoke Jackson Provider instead of Moxy. You will need jackson packages in your pom xml.

https://stackoverflow.com/a/60319306/5076414



来源:https://stackoverflow.com/questions/4944506/jaxb-a-cycle-is-detected-in-the-object-graph

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