WD1X.COM - 问答一下,轻松解决,电脑应用解决专家
主板显卡CPU内存显示器
硬盘维修显卡维修显示器维修
注册表系统命令DOS命令Win8
存储光存储鼠标键盘
内存维修打印机维修
WinXPWin7Win11Linux
硬件综合机箱电源散热器手机数码
主板维修CPU维修键盘鼠标维修
Word教程Excel教程PowerPointWPS
网络工具系统工具图像工具
数据库javascript服务器
PHP教程CSS教程XML教程

JSON、XML互转

更新时间:2021-06-07 10:15 作者:佚名点击:

在平时的开发中,有时候会用到JSON和XML的互转

  • net.sf.json-lib.json-lib包提供一些互转的方法;
  • com.alibaba.fastjson并没有提供;

但是现在用FastJSON的人越来越多,好多人在面临到JSON到XML互转的时候还是有些束手无策,现在写一个特别好用的工具类,分享给大家,一如既往的好用。

1、首先,推荐你用maven,然后不用多讲

<!-- https://mvnrepository.com/artifact/de.odysseus.staxon/staxon --> <dependency> <groupId>de.odysseus.staxon</groupId> <artifactId>staxon</artifactId> <version>1.3</version> </dependency>

这个复制粘贴丢到pom.xml文件里面,然后开始直接丢代码:

/**
* @ClassName StaxonUtils
* @Description 实现JSON--XML互转
* @author watermelon_code
* @Date 2017年7月19日 上午10:49:48
* @version 1.0.0
*/
public class StaxonUtils {
/**
* @Description: json string convert to xml string
* @author watermelon_code
* @date 2017年7月19日 上午10:50:32
*/
public static String json2xml(String json) {
StringReader input = new StringReader(json);
StringWriter output = new StringWriter();
JsonXMLConfig config = new JsonXMLConfigBuilder().multiplePI(false).repairingNamespaces(false).build();
try {
XMLEventReader reader = new JsonXMLInputFactory(config).createXMLEventReader(input);
XMLEventWriter writer = XMLOutputFactory.newInstance().createXMLEventWriter(output);
writer = new PrettyXMLEventWriter(writer);
writer.add(reader);
reader.close();
writer.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
output.close();
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return output.toString();
}
/**
* @Description: json string convert to xml string ewidepay ues only
* @author watermelon_code
* @date 2017年7月19日 上午10:50:32
*/
public static String json2xmlPay(String json) {
StringReader input = new StringReader(json);
StringWriter output = new StringWriter();
JsonXMLConfig config = new JsonXMLConfigBuilder().multiplePI(false).repairingNamespaces(false).build();
try {
XMLEventReader reader = new JsonXMLInputFactory(config).createXMLEventReader(input);
XMLEventWriter writer = XMLOutputFactory.newInstance().createXMLEventWriter(output);
writer = new PrettyXMLEventWriter(writer);
writer.add(reader);
reader.close();
writer.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
output.close();
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (output.toString().length() >= 38) {// remove <?xml version="1.0" encoding="UTF-8"?>
return "<xml>" + output.toString().substring(39) + "</xml>";
}
return output.toString();
}
/**
* @Description: xml string convert to json string
* @author watermelon_code
* @date 2017年7月19日 上午10:50:46
*/
public static String xml2json(String xml) {
StringReader input = new StringReader(xml);
StringWriter output = new StringWriter();
JsonXMLConfig config = new JsonXMLConfigBuilder().autoArray(true).autoPrimitive(true).prettyPrint(true).build();
try {
XMLEventReader reader = XMLInputFactory.newInstance().createXMLEventReader(input);
XMLEventWriter writer = new JsonXMLOutputFactory(config).createXMLEventWriter(output);
writer.add(reader);
reader.close();
writer.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
output.close();
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return output.toString();
}
/**
* @Description: 去掉转换xml之后的换行和空格
* @author watermelon_code
* @date 2017年8月9日 下午4:05:44
*/
public static String json2xmlReplaceBlank(String json) {
String str = StaxonUtils.json2xml(json);
String dest = "";
if (str != null) {
Pattern p = Pattern.compile("s*| |
|
");
Matcher m = p.matcher(str);
dest = m.replaceAll("");
}
return dest;
}
}

看效果吧:


public static void main(String[] args) {
JSONObject json = new JSONObject();
json.put("name", "jack");
json.put("age", 25);
String xmlstr = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><FromUserName><![CDATA[fromUser]]></FromUserName><CreateTime>1348831860</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[thisisatest]]></Content><MsgId>1234567890123456</MsgId></xml>";
System.out.println("JSON-->XML:");
System.out.println("JSON:" + json.toJSONString());
System.out.println("---------------------------------------------------------------");
System.out.println("普通转XML带格式:
" + StaxonUtils.json2xml(json.toJSONString()));
System.out.println("---------------------------------------------------------------");
System.out.println("转XML去掉头部、前后补充<XML>:
" + StaxonUtils.json2xmlPay(json.toJSONString()));
System.out.println("---------------------------------------------------------------");
System.out.println("普通转XML去掉空格换行:
" + StaxonUtils.json2xmlReplaceBlank(json.toJSONString()));
System.out.println("---------------------------------------------------------------");
System.out.println("XML转JSON:
" + StaxonUtils.xml2json(xmlstr));
}

运行结果:


JSON-->XML:
JSON:{"name":"jack","age":25}
---------------------------------------------------------------
普通转XML带格式:
<?xml version="1.0" encoding="UTF-8"?>
<name>jack</name>
<age>25</age>
---------------------------------------------------------------
转XML去掉头部、前后补充<XML>:
<xml><name>jack</name>
<age>25</age>
</xml>
---------------------------------------------------------------
普通转XML去掉空格换行:
<?xmlversion="1.0"encoding="UTF-8"?><name>jack</name><age>25</age>
---------------------------------------------------------------
XML转JSON:
{
"xml" : {
"ToUserName" : "toUser",
"FromUserName" : "fromUser",
"CreateTime" : 1348831860,
"MsgType" : "text",
"Content" : "thisisatest",
"MsgId" : 1234567890123456
}
}

那么这次的轮子到这里就结束了。

TO BE CONTINUE !

顶一下
(0)
0%
踩一下
(0)
0%
------分隔线----------------------------
你可能感兴趣的内容