如何将json转为xml?
步骤:
一:
str中传入json字符串。
json字符串可以在前端用JSON.stringify(json);来生成。其中json是字符串。
如:
var json = {
"message":{
"item":[{
"property":"她们所居住的地方"
},{
"property":"她们所居住的地方1"
},{
"property":"http://news.ifeng.com/a/20150924/44725669_0.shtml"
},{
"property":{
"item":[
{"property":"http://y2.ifengimg.com/a/2015_39/0baff630c44196b.jpg"},
{"property":"有时候你会因为一个镜头"}
]
}
}
]
}
}
然后可以通过:JSON.stringify(json);获得 str。
public String jsonToXml(String str) {
JSON jsonObject = JSONSerializer.toJSON(str);
JSONObject jsob = (JSONObject) jsonObject;
Element el = createXml(jsob, null);
return el.asXML();
}
二:
用于循环
public Element createXml(JSONObject jsob, Element root) {
if (jsob.isNullObject()) {
//jsob为空
} else {
Object[] object = jsob.names().toArray();
Arrays.sort(object);
for (int i = 0; i < object.length; i++) {
String name = (String) object[i];
Element el = null;
if (root != null) {
el = root.addElement(name);
}
Object value = jsob.get(name);
if (value instanceof JSONArray) {
if (root == null) {
root = DocumentHelper.createElement(name);
} else {
root = el;
}
JSONArray array = (JSONArray) value;
for (int j = 0; j < array.size(); j++) {
JSONObject item = (JSONObject) array.get(j);
createXml(item, root);
}
} else if (value instanceof JSONObject) {
if (root == null) {
root = DocumentHelper.createElement(name);
} else {
root = el;
}
createXml((JSONObject) value, root);
} else {
if (root == null) {
root = DocumentHelper.createElement(name);
el = root;
}
el.addCDATA((String) value);
}
}
}
return root;
}
注释:此方法用到的
import net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import org.dom4j.*;
maven 中需要引入依赖:
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.2.3</version>
<classifier>jdk15</classifier>
</dependency>
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
</dependency>
其中json-lib引入之后maven会自动下载:
net.sf.json-lib:json-lib:jdk15:2.2.3
net.sf.ezmorph:ezmorph:1.0.6
强调:一定要加入jdk15不然net.sf.ezmorph:ezmorph:1.0.6不会自动引入。