如何使用 JAXB 参考实现将 JAXB 对象序列化为 JSON? [英] How to serialize JAXB object to JSON with JAXB reference implementation?

查看:45
本文介绍了如何使用 JAXB 参考实现将 JAXB 对象序列化为 JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理的项目使用 JAXB 参考实现,即类来自 com.sun.xml.bind.v2.* 包.

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

我有一个类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 表示:

I want to use a JAXB marshaller to get a JSON representation of a User object:

@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?

The marshalled data is in XML format, not JSON format. How can I instruct the JAXB reference implementation to output JSON?

推荐答案

JAXB 参考实现不支持 JSON,需要添加类似 JacksonMoxy

JAXB reference implementation does not support JSON, you need to add a package like Jackson or 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);

查看示例此处

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

查看示例此处

这篇关于如何使用 JAXB 参考实现将 JAXB 对象序列化为 JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆