JAXB un-marshaling返回null

时间:2014-05-29 21:12:27

标签: java jaxb

我有一个具有以下结构的课程

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
@XmlSeeAlso({
Child.class
})
public abstract class Parent implements Serializable{}

并且

public class Child extends Parent implements Serializable{


  private String attribute;

  private List<String> values = new ArrayList<String>() ;
}

因此,在编组子对象时,它会在数据库中成功保存为:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Child >
    <attribute>age</attribute>
    <values>1</values>
    <values>2</values>
</Child >

问题是在解组该对象时,unmarshal函数返回null。

JAXB.unmarshal(reader, Parent.class)

您能告诉我们问题是什么,以及如何解决?

提前致谢

1 个答案:

答案 0 :(得分:1)

取消编组时,您必须:

  • 以XML的根目录提供标有@XMLRootElement的元素。
  • 将您的类定义为完全兼容的Java Bean(在属性上获取/设置方法)。

以下代码对我有用: 的 Parent.java

package dummy;

import java.io.Serializable;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSeeAlso;

@XmlRootElement
@XmlSeeAlso({
Child.class
})
public abstract class Parent implements Serializable{}

孩子(使用小型主要方法编组和解组相同的有效负载)

package dummy;

import java.io.ByteArrayInputStream;
import java.io.Serializable;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Child extends Parent implements Serializable
{

private String attribute;

private List<String> values = new ArrayList<String>();

/**
 * @return the attribute
 */
public String getAttribute()
{
    return attribute;
}

/**
 * @param attribute
 *            the attribute to set
 */
public void setAttribute(String attribute)
{
    this.attribute = attribute;
}

/**
 * @return the values
 */
public List<String> getValues()
{
    return values;
}

/**
 * @param values
 *            the values to set
 */
public void setValues(List<String> values)
{
    this.values = values;
}

public static void main(String[] args) throws JAXBException
{
    JAXBContext context = JAXBContext.newInstance(Parent.class);

    Child child = new Child();
    child.setAttribute("dummy");
    child.setValues(Arrays.asList("value1", "value2"));

    StringWriter writer = new StringWriter();

    context.createMarshaller().marshal(child, writer);

    System.out.println(writer.getBuffer().toString());

    Child unmarshalledChild = (Child) context.createUnmarshaller().unmarshal(new    ByteArrayInputStream(writer.getBuffer().toString().getBytes()));
    System.out.println("attribute: " + unmarshalledChild.attribute);
    System.out.println("values: " + unmarshalledChild.values);

}   

}

成功输出:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?><child>   <attribute>dummy</attribute><values>value1</values><values>value2</values></child>
attribute: dummy
values: [value1, value2]