栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

注意: 我是 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输出

请注意

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

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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/413718.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号