如何使用JAXB参考实现将JAXB对象序列化为JSON?

6

我正在处理的项目使用JAXB参考实现,也就是说这些类都来自com.sun.xml.bind.v2.*包。

我有一个名为User的类:

package com.example;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "user")
public class User {
    private String email;
    private String password;

    public User() {
    }

    public User(String email, String password) {
        this.email = email;
        this.password = password;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

}

我想使用JAXB marshaller将User对象转换成JSON格式:

@Test
public void serializeObjectToJson() throws JsonProcessingException, JAXBException {
    User user = new User("user@example.com", "mySecret");
    JAXBContext jaxbContext = JAXBContext.newInstance(User.class);

    Marshaller marshaller = jaxbContext.createMarshaller();

    StringWriter sw = new StringWriter();
    marshaller.marshal(user, sw);

    assertEquals( "{\"email\":\"user@example.com\", \"password\":\"mySecret\"}", sw.toString() );
}

序列化数据是以XML格式而非JSON格式进行的。 如何指示JAXB参考实现输出JSON?
1个回答

21

JAXB参考实现不支持JSON,您需要添加像JacksonMoxy这样的包。

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

请参考这里的示例。

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

请查看此处的示例。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接