2012-01-31 75 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