0.pom文件
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20180813</version>
</dependency>
1.XML字符串 -> JSON字符串
/**
* @Description: XML字符串 -> JSON字符串
* @Author: Yiang37
* @Date: 2021/08/12 10:53:47
* @Version: 1.0
*/
public static String xmlToJson(String xmlStr) {
JSONObject jsonObject = XML.toJSONObject(xmlStr);
return jsonObject.toString();
}
2.JSON字符串 - > XML字符串
/**
* @Description: JSON字符串 - > XML字符串
* @Author: Yiang37
* @Date: 2021/08/12 10:54:12
* @Version: 1.0
*/
public static String jsonToXml(String jsonStr) {
JSONObject jsonObject = new JSONObject(jsonStr);
String xmlStr = XML.toString(jsonObject);
return xmlStr;
}
3.参考demo
package com.boclink.utils;
import org.json.JSONObject;
import org.json.XML;
/**
* @Description: 报文格式转换
* @Class: MessageConversionUtils
* @Author: Yiang37
* @Date: 2021/8/12 10:36
* @Version: 1.0
*/
public class MessageConversionUtils {
// 头部追加 <?xml version="1.0" encoding="UTF-8"?>
final static String HEAD = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
// abc标签后追加 locale=" zh_CN"
final static String BLANK = " ";
final static String ADD_STR = "locale=\"zh_CN\"";
/**
* @Description: XML字符串 -> JSON字符串
* @Author: Yiang37
* @Date: 2021/08/12 10:53:47
* @Version: 1.0
*/
public static String xmlToJson(String xmlStr) {
JSONObject jsonObject = XML.toJSONObject(xmlStr);
return jsonObject.toString();
}
/**
* @Description: JSON字符串 - > XML字符串
* @Author: Yiang37
* @Date: 2021/08/12 10:54:12
* @Version: 1.0
*/
public static String jsonToXml(String jsonStr) {
JSONObject jsonObject = new JSONObject(jsonStr);
String xmlStr = XML.toString(jsonObject);
// abc标签后追加ADD_STR
String abc = appendXmlTagCon(xmlStr, "abc", ADD_STR);
return HEAD + abc;
}
/**
* @Description: xml的指定标签后 追加指定字符串
* @Author: Yiang37
* @Date: 2021/08/12 11:12:28
* @Version: 1.0
*/
public static String appendXmlTagCon(String xmlStr, String tagStr, String appendStr) {
// 计算标签出现的起始位置
int begin = xmlStr.indexOf(tagStr);
if (begin < 0){
// 未出现该字符串 返回原报文
return xmlStr;
}
// 计算追加字符串时的起始位置
int i = begin + tagStr.length();
// 插入追加的字符串
StringBuilder builder = new StringBuilder(xmlStr).insert(i, BLANK + appendStr);
return builder + "";
}
}