一尘不染

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

json

我正在研究的项目使用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编组器来获取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?


阅读 205

收藏
2020-07-27

共1个答案

一尘不染

JAXB参考实现不支持JSON,您需要添加一个包,例如JacksonMoxy

莫西

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

杰克逊

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

在这里查看示例

2020-07-27