2013-01-11 25 views
1

我有一個現有的複雜對象模型,我試圖編組JAXB xml。如果可能,我不想更改任何現有的域類。我有這個片段努力馬歇爾(使用Groovy)是否可以查看對象圖JAXB分析?

def marshallToFile(Object objectToMarshall, File location){ 

    def context = JAXBContext.newInstance(objectToMarshall.class) 

    def m = context.createMarshaller() 
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true) 

    location.withOutputStream { out -> 
     m.marshal(new JAXBElement(new QName("","rootTag"),objectToMarshall.class,objectToMarshall), out) 
    } 

} 

文件的問題是,對象圖是非常複雜的,JAXB告訴我com.sun.istack.internal.SAXException2: A cycle is detected in the object graph. This will cause infinitely deep XML: [email protected][Id=100053900] -> [email protected][Id=100053900]

有沒有什麼辦法讓有關的更多信息檢測週期?有誰知道一個工具,可以幫助分析圖形或列出它的圖形,以便我可以選擇週期?我有一種感覺,在這個圖表中有很多週期(這是舊的和複雜的),所以任何幫助,將不勝感激。

也許作爲一種替代方法,您可以告訴JAXB只深入'n'級或類似的東西,因此它不會創建無限深的XML嗎?

編輯:

相對於我的具體問題......原來,現有的域對象有一個 Object getThis()void setThis(Object obj)方法定義爲「漸」和「設置」的 this自我參照關鍵字

所以。那是導致我的週期的原因。這也突出了JAXB必須使用JavaBean方法定義來確定它將編組哪些屬性(我之前不知道)的事實。

但是,我認爲原始問題仍然存在,是否有任何好的工具用於分析/查看對象圖?

回答

0

您可以讓您的對象執行CycleRecoverable界面來查找有關週期的信息。

import java.util.*; 
import javax.xml.bind.annotation.*; 
import com.sun.xml.bind.CycleRecoverable; 

@XmlRootElement 
public class Department implements CycleRecoverable { 

    @XmlAttribute 
    public int id; 
    public String name; 
    public List<Employee> employees = new ArrayList<Employee>(); 

    public Object onCycleDetected(Context arg0) { 
     // Context provides access to the Marshaller being used: 
     System.out.println("JAXB Marshaller is: " + cycleRecoveryContext.getMarshaller()); 

     DepartmentPointer p = new DepartmentPointer(); 
     p.id = this.id; 
     return p; 
    } 

} 

更多信息

2

也許你可以引入Marshaller.Listener通過編組過程跟蹤和轉儲對象的信息,爲診斷的目的。有關更多信息,請參閱"Marshal Event Callbacks"(引用「外部偵聽器」的部分)。這不應該要求對現有域進行更改。

相關問題