JAXB for lists to be returned naturally for JSON or XML

前端 未结 1 1376
孤城傲影
孤城傲影 2021-01-17 23:09

I\'m using MOXy with Jersey to implement a RESTful API and want to return lists naturally for JSON and XML, by which I mean that the XML contains an element tag for the over

相关标签:
1条回答
  • 2021-01-17 23:46

    You could do the following to get the desired XML and JSON representations:

    Step #1 - Leverage @XMLElementWrapper

    Instead of:

    @XmlRootElement(name="organisation")
    @XmlAccessorType(XmlAccessType.FIELD)
    public class ExternalOrganisation {
    
       private String             name;
       private ExternalFacilities facilities;
       private ExternalLocations  locations;
    
       ...
    
    }
    

    You could do the following with @XmlElementWrapper (see: http://blog.bdoughan.com/2010/09/jaxb-collection-properties.html):

    @XmlRootElement(name="organisation")
    @XmlAccessorType(XmlAccessType.FIELD)
    public class ExternalOrganisation {
    
       private String             name;
    
       @XmlElementWrapper
       @XmlElementRef
       private List<ExternalFacility> facilities;
    
       @XmlElementWrapper
       @XmlElementRef
       private List<ExternalLocation>  locations;
    
       ...
    
    }
    

    Step #2 - Leverage MOXy's Wrapper as Array Name Property

    By specifying the wrapper as array name property, MOXy will use the value from @XmlElementWrapper as the JSON array name.

    import java.util.*;
    import javax.ws.rs.core.Application;
    import org.eclipse.persistence.jaxb.rs.MOXyJsonProvider;
    
    public class YourApplication  extends Application {
    
        @Override
        public Set<Class<?>> getClasses() {
            HashSet<Class<?>> set = new HashSet<Class<?>>(1);
            set.add(YourService.class);
            return set;
        }
    
        @Override
        public Set<Object> getSingletons() {
            MOXyJsonProvider moxyJsonProvider = new MOXyJsonProvider();
            moxyJsonProvider.setWrapperAsArrayName(true);
    
            HashSet<Object> set = new HashSet<Object>(1);
            set.add(moxyJsonProvider);
            return set;
        }
    
    } 
    

    For More Information

    • http://blog.bdoughan.com/2013/03/binding-to-json-xml-handling-collections.html
    • http://blog.bdoughan.com/2013/06/moxy-is-new-default-json-binding.html
    0 讨论(0)
提交回复
热议问题