其实很多时候,我们只需要鱼,而不是渔,呐,给你鱼。
在平时的开发中,有时候会用到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*|\t|\r|\n");
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带格式:\n" + StaxonUtils.json2xml(json.toJSONString()));
System.out.println("---------------------------------------------------------------");
System.out.println("转XML去掉头部、前后补充<XML>:\n" + StaxonUtils.json2xmlPay(json.toJSONString()));
System.out.println("---------------------------------------------------------------");
System.out.println("普通转XML去掉空格换行:\n" + StaxonUtils.json2xmlReplaceBlank(json.toJSONString()));
System.out.println("---------------------------------------------------------------");
System.out.println("XML转JSON:\n" + 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 !
作者:西瓜汁_柠檬水
链接:https://www.jianshu.com/p/029bf3a4f0fe
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
點擊查看更多內容
為 TA 點贊
評論
評論
共同學習,寫下你的評論
評論加載中...
作者其他優質文章
正在加載中
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦