【问题标题】:How to serialize JAXB object to JSON with JAXB reference implementation?如何使用 JAXB 参考实现将 JAXB 对象序列化为 JSON?
【发布时间】:2016-12-11 20:57:54
【问题描述】:

我正在处理的项目使用JAXB reference implementation,即类来自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?

【问题讨论】:

    标签: json jaxb


    【解决方案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);
    

    参见示例here

    杰克逊

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

    参见示例here

    【讨论】:

      猜你喜欢
      • 2011-01-13
      • 1970-01-01
      • 1970-01-01
      • 2014-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多