JsonXmlUtils.java 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. package thyyxxk.webserver.utils;
  2. import com.alibaba.fastjson.JSON;
  3. import com.alibaba.fastjson.JSONArray;
  4. import com.alibaba.fastjson.JSONObject;
  5. import com.alibaba.fastjson.serializer.ValueFilter;
  6. import lombok.extern.slf4j.Slf4j;
  7. import org.dom4j.*;
  8. import java.util.List;
  9. import java.util.Map;
  10. import java.util.Set;
  11. import java.util.regex.Pattern;
  12. /**
  13. * <p>
  14. * 描述:
  15. * </p>
  16. *
  17. * @author xc
  18. * @date 2022-03-28 16:28
  19. */
  20. @Slf4j
  21. public class JsonXmlUtils {
  22. /**
  23. * 解决 CDATA 问题
  24. */
  25. private static final Pattern PATTERN = Pattern.compile("[<>&\"',]");
  26. public static ValueFilter filter = (obj, s, v) -> {
  27. if (v == null) {
  28. return "";
  29. }
  30. return v;
  31. };
  32. private static String escape(String string) {
  33. return PATTERN.matcher(string).find() ? "<![CDATA[" + string + "]]>" : string;
  34. }
  35. public static boolean isEmpty(String str) {
  36. return str == null || str.trim().isEmpty() || "null".equals(str);
  37. }
  38. /**
  39. * updateXml 处理xml头,以及根标签
  40. */
  41. private static String updateXml(String xmlStr) {
  42. xmlStr = xmlStr.trim();
  43. if (StringUtil.isBlank(xmlStr)) {
  44. return xmlStr;
  45. }
  46. // 过滤非法字符
  47. xmlStr = xmlStr.replaceAll("[\\x00-\\x08\\x0b-\\x0c\\x0e-\\x1f]", "");
  48. StringBuilder xmlSb = new StringBuilder(xmlStr);
  49. if (!xmlStr.startsWith("<?")) {
  50. xmlSb.insert(0, "<?xml version=\"1.0\" encoding=\"utf-8\"?>");
  51. }
  52. int idx = xmlSb.indexOf("?>") + 2;
  53. xmlSb.insert(idx, "<root_chinadaas>").append("</root_chinadaas>");
  54. return xmlSb.toString();
  55. }
  56. /**
  57. * xml转json的核心循环方法
  58. *
  59. * @param element
  60. * @param json
  61. */
  62. private static void dom4j2Json(Element element, JSONObject json) {
  63. // 如果是属性
  64. for (Object o : element.attributes()) {
  65. Attribute attr = (Attribute) o;
  66. if (!isEmpty(attr.getValue())) {
  67. json.put("@" + attr.getName(), attr.getValue());
  68. }
  69. }
  70. List<Element> chdEl = element.elements();
  71. if (chdEl.isEmpty() && !isEmpty(element.getText())) { // 如果没有子元素,只有一个值
  72. json.put(element.getName(), element.getText());
  73. }
  74. for (Element e : chdEl) { // 有子元素
  75. if (!e.elements().isEmpty() || e.attributes().size() > 0) { // 子元素也有子元素,
  76. JSONObject chdjson = new JSONObject();
  77. dom4j2Json(e, chdjson);
  78. Object o = json.get(e.getName());
  79. if (o != null) {
  80. JSONArray jsona = null;
  81. if (o instanceof JSONObject) { // 如果此元素已存在,则转为jsonArray
  82. JSONObject jsono = (JSONObject) o;
  83. json.remove(e.getName());
  84. jsona = new JSONArray();
  85. jsona.add(jsono);
  86. jsona.add(chdjson);
  87. }
  88. if (o instanceof JSONArray) {
  89. jsona = (JSONArray) o;
  90. jsona.add(chdjson);
  91. }
  92. json.put(e.getName(), jsona);
  93. } else {
  94. if (!chdjson.isEmpty()) {
  95. json.put(e.getName(), chdjson);
  96. }
  97. }
  98. } else { // 子元素没有子元素
  99. for (Object o : element.attributes()) {
  100. Attribute attr = (Attribute) o;
  101. if (!isEmpty(attr.getValue())) {
  102. json.put("@" + attr.getName(), attr.getValue());
  103. }
  104. }
  105. if (!e.getText().isEmpty()) {
  106. json.put(e.getName(), e.getText());
  107. }
  108. }
  109. }
  110. }
  111. /**
  112. * xml转Json调用
  113. *
  114. * @throws DocumentException
  115. */
  116. public static JSONObject xml2Json(String xmlStr) throws DocumentException {
  117. xmlStr = updateXml(xmlStr);
  118. Document doc = DocumentHelper.parseText(xmlStr);
  119. JSONObject json = new JSONObject();
  120. dom4j2Json(doc.getRootElement(), json);
  121. return json;
  122. }
  123. /**
  124. * 根据at号获取所有的属性list
  125. */
  126. public static JSONObject getAttribute(JSONObject jdata) {
  127. JSONObject rdata = new JSONObject();
  128. try {
  129. Set<Map.Entry<String, Object>> setdata = jdata.entrySet();
  130. for (Map.Entry<String, Object> en : setdata) {
  131. if (en.getKey().startsWith("@")) {
  132. rdata.put(en.getKey().substring(1), escape((String) en.getValue()));
  133. }
  134. }
  135. } catch (Exception e) {
  136. e.printStackTrace();
  137. }
  138. return rdata;
  139. }
  140. /**
  141. * Json to xmlstr 核心循环方法
  142. */
  143. public static String json2Xmlstr(JSONObject jObj, StringBuffer buffer) {
  144. Set<Map.Entry<String, Object>> se = jObj.entrySet();
  145. for (Map.Entry<String, Object> en : se) {
  146. switch (en.getValue().getClass().getName()) {
  147. case "com.alibaba.fastjson.JSONObject":
  148. JSONObject jo = jObj.getJSONObject(en.getKey());
  149. buffer.append("<").append(en.getKey());
  150. //处理xml标签的属性值
  151. JSONObject attrlist1 = getAttribute(jo);
  152. Set<Map.Entry<String, Object>> attr1 = attrlist1.entrySet();
  153. for (Map.Entry<String, Object> amap : attr1) {
  154. buffer.append(" ").append(amap.getKey()).append("=\"").append(escape((String) amap.getValue())).append("\"");
  155. }
  156. buffer.append(">");
  157. if (jo.containsKey(en.getKey())) {
  158. //标签直接有值的话,直接赋值
  159. buffer.append(jo.getString(en.getKey()));
  160. } else {
  161. json2Xmlstr(jo, buffer);
  162. }
  163. buffer.append("</").append(en.getKey()).append(">");
  164. break;
  165. case "com.alibaba.fastjson.JSONArray":
  166. JSONArray jarray = jObj.getJSONArray(en.getKey());
  167. for (int i = 0; i < jarray.size(); i++) {
  168. buffer.append("<").append(en.getKey());
  169. JSONObject jsonobject = jarray.getJSONObject(i);
  170. //处理xml标签的属性值
  171. JSONObject attrlist2 = getAttribute(jsonobject);
  172. Set<Map.Entry<String, Object>> attr2 = attrlist2.entrySet();
  173. for (Map.Entry<String, Object> amap : attr2) {
  174. buffer.append(" ").append(amap.getKey()).append("=\"").append(escape((String) amap.getValue())).append("\"");
  175. }
  176. buffer.append(">");
  177. json2Xmlstr(jsonobject, buffer);
  178. buffer.append("</").append(en.getKey()).append(">");
  179. }
  180. break;
  181. case "java.lang.String":
  182. if (!en.getKey().startsWith("@")) {//@号的是属性,在前面已经处理过,这里就不处理了
  183. buffer.append("<").append(en.getKey()).append(">").append(escape((String) en.getValue()));
  184. buffer.append("</").append(en.getKey()).append(">");
  185. }
  186. break;
  187. }
  188. }
  189. return buffer.toString();
  190. }
  191. /**
  192. * json转xml调用
  193. *
  194. * @param json
  195. * @return java.lang.String
  196. */
  197. public static String json2Xml(String json) {
  198. try {
  199. StringBuffer buffer = new StringBuffer();
  200. JSONObject jObj = JSON.parseObject(json);
  201. json2Xmlstr(jObj, buffer);
  202. return buffer.toString();
  203. } catch (Exception e) {
  204. return "";
  205. }
  206. }
  207. }