使用JAXB将通用Java类绑定到JSON

时间:2010-08-06 09:32:54

标签: json jaxb jersey

我有以下java类

@XmlRootElement
@XmlSeeAlso(DataClass.class)
public static class EnvelopeClass<T> {

    @XmlElement
    public String version;

    @XmlElement
    public T data;

    EnvelopeClass() {
    }

    EnvelopeClass(String version, T data) {
        this.version = version;
        this.data = data;
    }

}

@XmlRootElement
public static class DataClass {

    @XmlElement
    public String name;

    DataClass() {
    }

    DataClass(String name) {
        this.name = name;
    }

}

我正在创建它的实例并将其编组为json

EnvelopeClass<DataClass> dataClassEnvelopeClass = new EnvelopeClass<DataClass>("1.0", new DataClass("myName"));

我有下一个结果:

{"version":"1.0","data":{"@type":"dataClass","name":"myName"}}

我不想在json “@ type”中输入类型信息:“dataClass”,换句话说我希望得到下一个结果:

{"version":"1.0","data":{"name":"myName"}}

当EnvelopeClass没有Generics时,我确实得到了这个结果。

有办法做到这一点吗?

1 个答案:

答案 0 :(得分:6)

要获得所需的行为,可以在data属性上使用@XmlAnyElement而不是@XmlElement。对于@XmlAnyElement属性,该值将对应于具有匹配的@XmlRootElement批注的类。

<强> EnvelopeClass

import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSeeAlso;

@XmlRootElement 
@XmlSeeAlso(DataClass.class) 
public class EnvelopeClass<T> { 

    @XmlElement 
    public String version; 

    @XmlAnyElement
    public T data; 

    EnvelopeClass() { 
    } 

    EnvelopeClass(String version, T data) { 
        this.version = version; 
        this.data = data; 
    } 

}

<强>数据类

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name="data") 
public class DataClass { 

    @XmlElement 
    public String name; 

    DataClass() { 
    } 

    DataClass(String name) { 
        this.name = name; 
    } 

}

<强>演示

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(EnvelopeClass.class);

        DataClass data = new DataClass("myName");
        EnvelopeClass envelope = new EnvelopeClass<DataClass>("1.0", data);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(envelope, System.out);
    }
}