How to serialize JAXB object to JSON with JAXB reference implementation?

后端 未结 1 894
自闭症患者
自闭症患者 2020-12-11 07:53

The project I\'m working on uses the JAXB reference implementation, i.e. classes are from the com.sun.xml.bind.v2.* packages.

I have a class User<

相关标签:
1条回答
  • 2020-12-11 08:16

    JAXB reference implementation does not support JSON, you need to add a package like Jackson or Moxy

    Moxy

     //import org.eclipse.persistence.jaxb.JAXBContextProperties;
    
     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[] {User.class}, properties);
    
     Marshaller marshaller = jc.createMarshaller();
     marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
     marshaller.marshal(user, System.out);
    

    See example here

    Jackson

    //import org.codehaus.jackson.map.AnnotationIntrospector;
    //import org.codehaus.jackson.map.ObjectMapper;
    //import org.codehaus.jackson.xc.JaxbAnnotationIntrospector;
    
    ObjectMapper mapper = new ObjectMapper();  
    AnnotationIntrospector introspector = new JaxbAnnotationIntrospector(mapper.getTypeFactory());
    mapper.setAnnotationIntrospector(introspector);
    
    String result = mapper.writeValueAsString(user);
    

    See example here

    0 讨论(0)
提交回复
热议问题