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

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

本文介绍了使用JAXB将通用Java类绑定到JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下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

I'm creating its instance and marshaling it to json

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

我有下一个结果:

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

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

I do not want to have type type information in the json "@type":"dataClass", in other words I want to have next result:

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

当EnvelopeClass没有Generics时,我的结果正好。

Exactly this result I have when EnvelopeClass doesn't have Generics.

有没有办法做到这一点?

Is there a way to do this?

推荐答案

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

To get the desired behaviour, you can use @XmlAnyElement on the data property instead of @XmlElement. For the @XmlAnyElement property the value will correspond to a class with the matching @XmlRootElement annotation.

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;
    }

}

DataClass

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);
    }
}

这篇关于使用JAXB将通用Java类绑定到JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 20:20