tags:

views:

86

answers:

1

I have the following java class

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

}

I'm creating its instance and marshaling it to json

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

I have next result:

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

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

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

Is there a way to do this?

A: 

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

}

Demo

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);
    }
}
Blaise Doughan
Thank you - it works, the only change I made is - I annotated name for DataClass:`@XmlRootElement(name = "data")``public class DataClass { ...`
Vladimir Sorokin