这几天需要JSON与XML之间转换的工具类,网上搜了好多都不是自己需要的,于是自己编写了一个。
一、JSON转XML
(1)JSONbean 转换成XML
public class People {
People(int id,String name){
this.id = id;
this.name = name;
}
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
JSONbean方法:
/**
* JsonObject转换成xml
*
* @param json
* @return
*/
public static String JsonBean2XmlString(JSONObject json){
System.out.println("JsonBean转换成xml:");
System.out.println("json:"+json);
StringBuffer sb = new StringBuffer("<xml><p>");
for(Object key : json.keySet()){
sb.append("<").append(key).append(">");
Object value = json.get(key);
//判断value是否含有JSONArray
JSONObject jsonV = ((JSONObject)value);
for(Object key2 : jsonV.keySet()){
sb.append("<").append(key2).append(">");
Object value2 = jsonV.get(key2);
sb.append(value2);
sb.append("</").append(key2).append(">");
}
sb.append("</").append(key).append(">");
}
sb.append("</p></xml>");
return sb.toString();
}
main测试:
JSONObject json = new JSONObject();
People p = new People(9203,"xiaobao");
People p2 = new People(943,"xiaoxiao");
json.put("p1", p);
json.put("p2", p2);
System.out.println(JsonBean2XmlString(json));
测试输出结果:
JsonBean转换成xml:
json:{"p1":{"id":9203,"name":"xiaobao"},"p2":{"id":943,"name":"xiaoxiao"}}
<xml><p><p1><id>9203</id><name>xiaobao</name></p1><p2><id>943</id><name>xiaoxiao</name></p2></p></xml>
(2)多层嵌套的JSON转换
如:{"p":{"p1":{"p2":{"id":2222,"name":"xiao2"}},"name":"xiao3"},"id2":"iii","name2":"ffff"}
/**
* Json多层数据结构转换成xml
* @param json
* @return
*/
public static String Json2XmlString(String jsonStr){
System.out.println("json转换成xmlString:");
JSONObject json = JSONObject.fromObject(jsonStr);
StringBuffer sb = new StringBuffer("<xml>");
for(Object key : json.keySet()){
sb.append("<").append(key).append(">");
Object value = json.get(key);
sb.append(iteraorJson(value));
sb.append("</").append(key).append(">");
}
sb.append("</xml>");
return sb.toString();
}
/**
* 迭代判断value是否还包含jSONObject
* @param value
* @return
*/
public static String iteraorJson(Object value){
StringBuffer sb = new StringBuffer("");
if((value.toString().contains(":"))){
JSONObject json = ((JSONObject)value);
for(Object key : json.keySet()){
sb.append("<").append(key).append(">");
Object value2 = json.get(key);
sb.append(iteraorJson(value2));
sb.append("</").append(key).append(">");
}
}else{
sb.append(value);
}
return sb.toString();
}
测试:
String jsonStr = "{\"p\":{\"p1\":{\"p2\":{\"id\":2222,\"name\":\"xiao2\"}},\"name\":\"xiao3\"},\"id2\":\"iii\",\"name2\":\"ffff\"}";
System.out.println("jsonStr:"+jsonStr);
System.out.println(Json2XmlString(jsonStr));
结果输出:
jsonStr:{"p":{"p1":{"p2":{"id":2222,"name":"xiao2"}},"name":"xiao3"},"id2":"iii","name2":"ffff"}
json转换成xmlString:
<xml><p><p1><p2><id>2222</id><name>xiao2</name></p2></p1><name>xiao3</name></p><id2>iii</id2><name2>ffff</name2></xml>