java marshaller_使用Marshaller将Java对象转换为Json

小编典典

如果将MOXy用作JAXB提供程序,以下是如何完成的。

JAVA模型

顾客

import java.util.*;

import javax.xml.bind.annotation.*;

@XmlRootElement(namespace="http://www.example.com")

@XmlType(namespace="http://www.example.com")

@XmlAccessorType(XmlAccessType.FIELD)

public class Customer {

@XmlAttribute

private int id;

@XmlElement(namespace="http://www.example.com")

private String firstName;

@XmlElement(namespace="http://www.example.com", nillable=true)

private String lastName;

@XmlElement(namespace="http://www.example.com")

private List phoneNumbers = new ArrayList();

}

电话号码

import javax.xml.bind.annotation.*;

@XmlAccessorType(XmlAccessType.FIELD)

public class PhoneNumber {

@XmlAttribute

private String type;

@XmlValue

private String number;

}

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

演示代码

input.xml

Jane

555-1111

演示版

在下面的演示代码中,我们将使用相同的JAXB元数据将XML文档转换为Java对象,然后将这些对象转换回JSON。使用MOXy,您可以通过在上设置属性来指定JSON输出Marshaller。

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/forum15357366/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输出

以下是JSON输出。注意,没有名称空间或XML属性对应的指示符。还要注意,大小为1的集合已正确表示为JSON数组(其他方法存在的问题)。

{

"id" : 123,

"firstName" : "Jane",

"lastName" : null,

"phoneNumbers" : [ {

"type" : "work",

"value" : "555-1111"

} ]

}

2020-07-27

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值