java中Xml、json之间的相互转换
project格式是:

jar包是一个一个检出来的,还算干净了。
代码:
工具类:

package exercise.xml;
import net.sf.json.JSON;
import net.sf.json.JSONSerializer;
import net.sf.json.xml.XMLSerializer;
import org.jdom.Document;
public class XmlExercise {
/**
* 将xml字符串<STRONG>转换</STRONG>为JSON字符串
*
* @param xmlString
* xml字符串
* @return JSON<STRONG>对象</STRONG>
*/
public static String xml2json(String xmlString) {
XMLSerializer xmlSerializer = new XMLSerializer();
JSON json = xmlSerializer.read(xmlString);
return json.toString(1);
}
/**
* 将xmlDocument<STRONG>转换</STRONG>为JSON<STRONG>对象</STRONG>
*
* @param xmlDocument
* XML Document
* @return JSON<STRONG>对象</STRONG>
*/
public static String xml2json(Document xmlDocument) {
return xml2json(xmlDocument.toString());
}
/**
* JSON(数组)字符串<STRONG>转换</STRONG>成XML字符串
*
* @param jsonString
* @return
*/
public static String json2xml(String jsonString) {
XMLSerializer xmlSerializer = new XMLSerializer();
return xmlSerializer.write(JSONSerializer.toJSON(jsonString));
// return xmlSerializer.write(JSONArray.fromObject(jsonString));//这种方式只支持JSON数组
}
}

测试类:

package exercise.xml;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class XmlTest extends XmlExercise {
public static void main(String[] args) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("username", "horizon");
JSONArray jsonArray = new JSONArray();
JSONObject dataJson = new JSONObject();
jsonArray.add(jsonObject);
//jsonArray.add(jsonObject);
dataJson.put("data", jsonArray);
System.out.println(dataJson.toString());
String xml = json2xml(dataJson.toString());
System.out.println("xml:" + xml);
String str = xml2json(xml);
System.out.println("to_json" + str);
}
}
本文介绍了一种在Java中实现XML与JSON格式互相转换的方法。通过使用XMLSerializer和JSONSerializer工具类,可以轻松地将XML数据转换为JSON对象,或将JSON数据转换回XML格式。文章提供了具体的代码示例,展示了如何进行转换,并验证了转换过程的正确性。

被折叠的 条评论
为什么被折叠?



