使用JAXB序列化Java对象

时间:2015-10-13 12:50:17

标签: java xml serialization jaxb

我有以下两个类层次结构:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name="Dictionary",propOrder={"description"})
public class DictionaryDto implements Serializable, Descriptionable {

    private static final long serialVersionUID = 1L;

    @XmlAttribute(required=true)
    private String id;

    @XmlElement(name="Description")
    private String description;

    public DictionaryDto() {
    }

    public DictionaryDto(String id, String description) {
        this.id = id;
        this.description = description;
    }

    //getters and setters follows...
}

public class DictionaryProvinceDto extends DictionaryDto {

    private String code;
    private static final long serialVersionUID = 1L;

    public DictionaryProvinceDto () {
        super();
    }

    public DictionaryProvinceDto (String id, String description, String code) {
        super(id, description);
        this.code= code;
    }

    //getters and setters follows...
}

其中Descriptionable是一个声明唯一方法String getDescription()

的接口

我正在尝试在XML中序列化一个DictionaryProvinceDto类型的对象,但我得到了

<Province id="030">
    <code>AN</code>
</Province>

期望的输出:

<Province id="030">
    <code>AN</code>
    <description>my funny province</description>
</Province>

有没有人可以解释为什么我没有得到我的期望?

1 个答案:

答案 0 :(得分:0)

@XmlRootElement(name="Province")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name="DictionaryProvince")
public class DictionaryProvince extends Dictionary {
    @XmlElement(required=true)
    private String code;
    // ...
}

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name="Dictionary",propOrder={"description"})
public class Dictionary {  // no need for Serializable
    // ... as before
}

@XmlRegistry
public class ObjectFactory {
    private final static QName _dict_QNAME = new QName("", "dict");
    public ObjectFactory() {
    }
    @XmlElementDecl(namespace = "", name = "Province")
    public JAXBElement<DictionaryProvince> 
    createDictionaryProvince(DictionaryProvince value) {
        return new JAXBElement<DictionaryProvince>(_dict_QNAME, DictionaryProvince.class, null, value);
    }
}

最后是编组代码:

DictionaryProvince dp = new DictionaryProvince( "id", "prov", "code" );
JAXBContext jc = JAXBContext.newInstance( PACKAGE );
Marshaller m = jc.createMarshaller();
JAXBElement<DictionaryProvince> jbe;
jbe = wrap( null, "Province", dp );
m.marshal( jbe, sw );

方法换行:

<T> JAXBElement<T> wrap( String ns, String tag, T o ){
    QName qtag = new QName( ns, tag );
    Class<?> clazz = o.getClass();
    @SuppressWarnings( "unchecked" )
    JAXBElement<T> jbe = new JAXBElement( qtag, clazz, o );
    return jbe;
}