Is there a possibility to hide the “@type” entry when marshalling subclasses to JSON using EclipseLink MOXy (JAXB)?

后端 未结 1 1706
暖寄归人
暖寄归人 2021-01-13 06:34

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

相关标签:
1条回答
  • 2021-01-13 06:45

    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.

    Java Model

    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 Code

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

    For More Information

    • http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html
    • http://blog.bdoughan.com/2012/05/moxy-as-your-jax-rs-json-provider.html
    0 讨论(0)
提交回复
热议问题