1、引入依赖
// https://mvnrepository.com/artifact/net.sf.json-lib/json-lib
compile ("net.sf.json-lib:json-lib:${jsonlibVersion}")
// https://mvnrepository.com/artifact/org.json/json
compile group: 'org.json', name: 'json', version: "${orgJsonVersion}"
compile ("xom:xom:${xomVersion}")
jsonlibVersion=2.4:jdk15
orgJsonVersion=20190722
xomVersion=1.2.5
2、转化工具类
package com.iscas.common.web.tools.jsonxml;
import org.apache.commons.lang.StringUtils;
import org.json.JSONObject;
import org.json.XML;
import java.io.IOException;
/**
* JSON-XML转换工具类
*
* @author zhuquanwen
* @vesion 1.0
* @date 2020/1/20 15:46
* @since jdk1.8
*/
public class JsonXmlConvertUtils {
/**
* 将json转为XML
* */
public static String json2Xml(String json) {
net.sf.json.xml.XMLSerializer xmlSerializer = new net.sf.json.xml.XMLSerializer();
// 根节点名称
xmlSerializer.setRootName("json2xml");
// 不对类型进行设置
xmlSerializer.setTypeHintsEnabled(false);
String xmlStr = "";
net.sf.json.JSONObject jobj = net.sf.json.JSONObject.fromObject(json);
xmlStr = xmlSerializer.write(jobj);
//去掉根节点
xmlStr = StringUtils.substringAfter(xmlStr, "<json2xml>");
xmlStr = StringUtils.substringBeforeLast(xmlStr, "</json2xml>");
return xmlStr;
}
/**
* xml转为JSON
* */
public static String xml2Json(String xml) throws IOException {
JSONObject xmlJSONObj = XML.toJSONObject(xml);
return xmlJSONObj.toString();
}
}
3、测试
package com.iscas.common.web.tools.jsonxml;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import java.io.IOException;
/**
* //TODO
*
* @author zhuquanwen
* @vesion 1.0
* @date 2020/1/20 15:52
* @since jdk1.8
*/
@RunWith(JUnit4.class)
public class JsonXmlConvertUtilsTests {
/**
* json转为XML
* */
@Test
public void test0() {
String s = JsonXmlConvertUtils.json2Xml("{\n" +
"\t\"Proxy\": {\n" +
"\t\t\"defaultSettings\": {\n" +
"\t\t\t\"selfWebPath\": \"/sp/\",\n" +
"\t\t\t\"maxContentLength\": 1073741824,\n" +
"\t\t\t\"basePath\": \"/\",\n" +
"\t\t\t\"staticResourcePath\": \"F:/static\",\n" +
"\t\t\t\"port\": 8180,\n" +
"\t\t\t\"SO_BACKLOG\": 2097152,\n" +
"\t\t\t\"sslKeyPath\": \"C:/Users/Administrator/local.jks\"\n" +
"\t\t}\n" +
"\t}\n" +
"}");
System.out.println(s);
}
/**
* xml转为json
* */
@Test
public void test() throws IOException {
String s = JsonXmlConvertUtils.xml2Json("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<Proxy>\n" +
"\t<defaultSettings>\n" +
"\t\t<port>8180</port>\n" +
"\t\t<basePath>/</basePath>\n" +
"\t\t<selfWebPath>/sp/</selfWebPath>\n" +
"\t\t<SO_BACKLOG>2097152</SO_BACKLOG>\n" +
"\t\t<maxContentLength>1073741824</maxContentLength>\n" +
"\t\t<!--<maxContentLength>102400000</maxContentLength>-->\n" +
"\t\t<sslKeyPath>C:/Users/Administrator/local.jks</sslKeyPath>\n" +
"\t\t<staticResourcePath>F:/static</staticResourcePath>\n" +
"\t</defaultSettings>\n" +
"</Proxy>");
System.out.println(s);
}
}