2012-01-31 123 views
3

我用xjc做了一些類。JAXB - List <Serializable>?

public class MyType { 

    @XmlElementRefs({ 
     @XmlElementRef(name = "MyInnerType", type = JAXBElement.class, required = false), 

    }) 
    @XmlMixed 
    protected List<Serializable> content; 

    public List<Serializable> getContent() { 
     if (content == null) { 
      content = new ArrayList<Serializable>(); 
     } 
     return this.content; 
    } 
} 

,但我不能使用

getContent().add(newItem); 

因爲MyInnerType無法序列化添加內部元件。 爲什麼它不是一個對象列表?我如何添加內部元素?

+0

你得到什麼錯誤? – Tudor 2012-01-31 14:50:58

+0

MyInnerType不是可序列化的 – bunnyjesse112 2012-01-31 15:02:22

回答

4

請看看herehere(一定要確定您的方案)。

從第二個環節:

<!-- schema fragment having mixed content --> 
<xs:complexType name="letterBody" mixed="true"> 
<xs:sequence> 
    <xs:element name="name" type="xs:string"/> 
    <xs:element name="quantity" type="xs:positiveInteger"/> 
    <xs:element name="productName" type="xs:string"/> 
    <!-- etc. --> 
</xs:sequence> 
</xs:complexType> 
<xs:element name="letterBody" type="letterBody"/> 


// Schema-derived Java code: 
// (Only annotations relevant to mixed content are shown below, 
// others are ommitted.) 
import java.math.BigInteger; 
public class ObjectFactory { 
    // element instance factories 
    JAXBElement<LetterBody> createLetterBody(LetterBody value); 
    JAXBElement<String>  createLetterBodyName(String value); 
    JAXBElement<BigInteger> createLetterBodyQuantity(BigInteger value); 
    JAXBElement<String>  createLetterBodyProductName(String value); 
    // type instance factory 
    LetterBody> createLetterBody(); 
} 

public class LetterBody { 
    // Mixed content can contain instances of Element classes 
    // Name, Quantity and ProductName. Text data is represented as 
    // java.util.String for text. 
    @XmlMixed 
    @XmlElementRefs({ 
      @XmlElementRef(name="productName", type=JAXBElement.class), 
      @XmlElementRef(name="quantity", type=JAXBElement.class), 
      @XmlElementRef(name="name", type=JAXBElement.class)}) 
    List getContent(){...} 
} 
+0

謝謝!真的幫助我! – bunnyjesse112 2012-02-03 08:06:37

+0

這確實有幫助。感謝您的鏈接! – 2017-02-03 03:04:14

+0

鏈接已損壞。新的鏈接,請? – ulab 2017-05-22 09:54:45

1

你認爲你應該在那裏添加什麼?我使用過類似的一代,並且有這樣的字段,期望它是字符串內容。

它可能會有助於顯示這是從生成的xsd。

+0

感謝您的回答。 MyInnerType不是一個字符串。爲什麼它會生成列表而不是列表?我是否需要在JAXBElement中包裝MyInnerType? – bunnyjesse112 2012-01-31 15:13:04

+1

這聽起來像是一個好主意,因爲你的對象是不可序列化的。但爲什麼不讓你的對象可序列化?這只是實現界面的問題。 – AHungerArtist 2012-01-31 16:09:14

相關問題