java xml to json xml 转json
目录
依赖
代码
日志
效果
依赖
dom4j dom4j 1.6.1 com.alibaba fastjson 1.2.32
代码
import java.io.File;import java.io.FileInputStream;import java.nio.ByteBuffer;import java.nio.channels.FileChannel;import java.util.List;import com.alibaba.fastjson.JSONArray;import com.alibaba.fastjson.JSONObject;import org.dom4j.*;public static void main(String[] args) throws DocumentException { String str="\r\n" + "\r\n" + "200\r\n" + "请求成功\r\n" + "\r\n" + "\r\n" + " \r\n" + " \r\n" + " value1\r\n" + " value2\r\n" + " value2\r\n" + " value2\r\n" + " \r\n" + " \r\n" + " ssss\r\n" + "\r\n" + "\r\n" + "\r\n" + ""; Document doc = DocumentHelper.parseText(str); JSONObject json = new JSONObject(); dom4j2Json(doc.getRootElement(), json); System.out.println("xml2Json:" + json.toJSONString()); } // xml转json public static JSONObject xml2Json(String xmlStr) throws DocumentException { Document doc = DocumentHelper.parseText(xmlStr); JSONObject json = new JSONObject(); dom4j2Json(doc.getRootElement(), json); return json; } // xml转json public static void dom4j2Json(Element element, JSONObject json) { // 如果是属性 for (Object o : element.attributes()) { Attribute attr = (Attribute) o; if (!isEmpty(attr.getValue())) { json.put("@" + attr.getName(), attr.getValue()); } } List chdEl = element.elements(); if (chdEl.isEmpty() && !isEmpty(element.getText())) {// 如果没有子元素,只有一个值 json.put(element.getName(), element.getText()); } for (Element e : chdEl) {// 有子元素 if (!e.elements().isEmpty()) {// 子元素也有子元素 JSONObject chdjson = new JSONObject(); dom4j2Json(e, chdjson); Object o = json.get(e.getName()); if (o != null) { JSONArray jsona = null; if (o instanceof JSONObject) {// 如果此元素已存在,则转为jsonArray JSONObject jsono = (JSONObject) o; json.remove(e.getName()); jsona = new JSONArray(); jsona.add(jsono); jsona.add(chdjson); } if (o instanceof JSONArray) { jsona = (JSONArray) o; jsona.add(chdjson); } json.put(e.getName(), jsona); } else { if (!chdjson.isEmpty()) { json.put(e.getName(), chdjson); } } } else {// 子元素没有子元素 for (Object o : element.attributes()) { Attribute attr = (Attribute) o; if (!isEmpty(attr.getValue())) { json.put("@" + attr.getName(), attr.getValue()); } } if (!e.getText().isEmpty()) { json.put(e.getName(), e.getText()); } } } } public static boolean isEmpty(String str) { if (str == null || str.trim().isEmpty() || "null".equals(str)) { return true; } return false; }
日志
xml2Json:{"STATUS":"200","DATA":{"RECORDS":{"RECORD":"ssss"}},"TIME":"20160513131050","DESC":"请求成功"}
ok
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
暂时没有评论,来抢沙发吧~