小编典典

使用Jackson API和JAXB注释将JSON转换为XML,反之亦然

json

我正在尝试编写一个可以接受XML或JSON输入并分别输出JSON或XML的代码。即,如果我提供XML,则应返回JSON,如果我提供JSON,则应返回XML输出。

有人告诉我使用Jackson API和JAXB注释是可能的。谁能帮我这个忙吗?


阅读 394

收藏
2020-07-27

共1个答案

小编典典

注意: 我是 EclipseLink
JAXB(MOXy)的
负责人,并且是
JAXB(JSR-222)
专家组的成员。

下面是一个示例,说明如何使用MOXy的JSON绑定来支持此用例。

JAVA模型

下面是一个用JAXB元数据注释的示例域模型。相同的元数据将用于对象到XML转换和对象到JSON转换。

顾客

import java.util.List;
import javax.xml.bind.annotation.*;

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Customer {

    private int id;

    private String firstName;

    @XmlElement(nillable=true)
    private String lastName;

    private List<PhoneNumber> phoneNumbers;

}

电话号码

import javax.xml.bind.annotation.*;

@XmlAccessorType(XmlAccessType.FIELD)
public class PhoneNumber {

    @XmlAttribute
    private String type;

    @XmlValue
    private String number;

}

XML输入

以下是我们将使用的XML输入。注意如何在元素上xsi:nil使用属性lastName来指示null值。还要注意phoneNumbers元素如何具有type属性。

<?xml version="1.0" encoding="UTF-8"?>
<customer>
   <id>123</id>
   <firstName>Jane</firstName>
   <lastName xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>
   <phoneNumbers type="work">555-1111</phoneNumbers>
</customer>

演示代码

jaxb.properties

要将MOXy指定为JAXB提供程序,您需要jaxb.properties在与域模型相同的程序包中包含一个名为的文件,并包含以下条目(请参阅:http : //blog.bdoughan.com/2011/05/specifying-
eclipselink-moxy-as -your.html):

javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory

演示版

以下演示代码将XML转换为域模型,然后再转换回JSON。

import java.io.File;
import javax.xml.bind.*;
import org.eclipse.persistence.jaxb.MarshallerProperties;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Customer.class);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        File xml = new File("src/forum14734741/input.xml");
        Customer customer = (Customer) unmarshaller.unmarshal(xml);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.setProperty(MarshallerProperties.MEDIA_TYPE, "application/json");
        marshaller.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT, false);
        marshaller.marshal(customer, System.out);
    }

}

JSON输出

请注意nulllastName键的值如何表示为正确的JSON。还要注意,type键如何不包含任何与XML表示中的XML属性相对应的特殊指示符。

{
   "id" : 123,
   "firstName" : "Jane",
   "lastName" : null,
   "phoneNumbers" : [ {
      "type" : "work",
      "value" : "555-1111"
   } ]
}
2020-07-27