xml转json
Posted jwcc
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了xml转json相关的知识,希望对你有一定的参考价值。
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
public static String xmlToJSON(String xml,int jsonType) {
JSONObject obj = new JSONObject();
try {
InputStream is = new ByteArrayInputStream(xml.getBytes("utf-8"));
SAXBuilder sb = new SAXBuilder();
Document doc = sb.build(is);
Element root = doc.getRootElement();
Map map=iterateElement(root);
obj.put(root.getName(),map);
return obj.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private static Map iterateElement(Element root) {
List childrenList = root.getChildren();
Element element = null;
Map map = new HashMap();
List list = null;
for (int i = 0; i < childrenList.size(); i++) {
list = new ArrayList();
element = (Element) childrenList.get(i);
if(element.getChildren().size()>0){
if(root.getChildren(element.getName()).size()>1){
if (map.containsKey(element.getName())) {
list = (List) map.get(element.getName());
}
list.add(iterateElement(element));
map.put(element.getName(), list);
}else{
map.put(element.getName(), iterateElement(element));
}
}else {
if(root.getChildren(element.getName()).size()>1){
if (map.containsKey(element.getName())) {
list = (List) map.get(element.getName());
}
list.add(element.getTextTrim());
map.put(element.getName(), list);
}else{
map.put(element.getName(), element.getTextTrim());
}
}
}
return map;
}
以上是关于xml转json的主要内容,如果未能解决你的问题,请参考以下文章