I\'m about to develop a JAX-RS based RESTful web service and I use MOXy (JAXB) in order to automatically generate my web service\'s JSON responses.
Everything is coo
You can wrap your object in an instance of JAXBElement
specifying the subclass being marshalled to get rid of the type key. Below is a full example.
Same as from the question, but with the following package-info
class added to specifying the field access to match those classes
@XmlAccessorType(XmlAccessType.FIELD)
package com.example.foo;
import javax.xml.bind.annotation.*;
Demo
import java.util.*;
import javax.xml.bind.*;
import javax.xml.namespace.QName;
import org.eclipse.persistence.jaxb.JAXBContextProperties;
public class Demo {
public static void main(String[] args) throws Exception {
Map<String, Object> properties = new HashMap<String, Object>(2);
properties.put(JAXBContextProperties.MEDIA_TYPE, "application/json");
properties.put(JAXBContextProperties.JSON_INCLUDE_ROOT, false);
JAXBContext jc = JAXBContext.newInstance(new Class[] {MySpecialResponse.class}, properties);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
MySpecialResponse msr = new MySpecialResponse();
marshaller.marshal(msr, System.out);
JAXBElement<MySpecialResponse> jaxbElement = new JAXBElement(new QName(""), MySpecialResponse.class, msr);
marshaller.marshal(jaxbElement, System.out);
}
}
Output
We see that when the object was marshalled an type
key was marshalled (corresponding to the xsi:type
attribute in the XML representation), because as MOXy is concerned it was necessary to distinguish between MyBasicResponse
and MySpecialResponse
. When we wrapped the object in an instance of JAXBElement
and qualified the type MOXy didn't need to add the type
key.
{
"type" : "mySpecialResponse"
}
{
}