我正在寻找一个与Cml中的XmlInclude相同的Java注释。
我在套接字上获得了XML结构。结构如下所示:
<Answer xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<FunctionReturnCode>0</FunctionReturnCode>
<AnswerObject xsi:type="Status">
<DoorOpen>79</DoorOpen>
</AnswerObject>
</Answer>
相应的Java类定义如下:
@XmlRootElement(name="Answer")
@XmlType(propOrder = {"functionReturnCode", "answerObject"})
public class Answer
{
private Object m_answerObject = null;
private long m_uiFunctionReturnCode = 0;
@XmlElement(name="FunctionReturnCode")
public long getFunctionReturnCode(){ return this.m_uiFunctionReturnCode; }
public void setFunctionReturnCode(long _uiFunctionReturnCode) { this.m_uiFunctionReturnCode = _uiFunctionReturnCode; }
@XmlElement(name="AnswerObject")
public Object getAnswerObject() { return this.m_answerObject; }
public void setAnswerObject(Object _answerObject) { this.m_answerObject = _answerObject;}
}
在C#中,类看起来像这样:
[XmlInclude(typeof(SelStatus))]
&LT;&LT;&LT;这对我来说似乎是一个神奇的观点 公共类答案:ICloneable
{
private uint m_uiFunctionReturnCode = 0;
private object m_answerObject = null;
.....Setters/Getters here as well
}
问题是,“AnswerObject”可以是任何类型的对象。在我的例子中,“AnswerObject”是一个“Status”类型的对象,但它也可以是一个字符串或者什么。
在C#中,我可以使用XmlSerializer对XML结构进行反序列化。在Java中,我使用以下内容:
JAXBContext context = JAXBContext.newInstance(Answer.class);
Unmarshaller unmarschaller = context.createUnmarshaller();
C#和Java(以及)自动处理字符串。但是如果有另一个对象,那么我可以通过XmlInclude其他已知类来宣告C#。 Java中有类似的内容吗?
答案 0 :(得分:0)
类型为Object的属性上的@XmlElement是正确的映射:
@XmlElement(name="AnswerObject")
public Object getAnswerObject() { return this.m_answerObject; }
public void setAnswerObject(Object _answerObject) { this.m_answerObject = _answerObject;}
您需要确保JAXBContext知道AnswerObject的任何可能值。您可以在创建JAXBContext时使这些类成为这些类:
JAXBContext.newInstance(Answer.class, ValueA.class, ValueB.class);
或者通过@XmlSeeAlso注释指定它们。
@XmlRootElement(name="Answer")
@XmlType(propOrder = {"functionReturnCode", "answerObject"})
@XmlSeeAlso{{ValueA.class, ValueB.class}
public class Answer
{
...
}