記錄下JSON和xml相互轉換的方法:
import java.io.File;
import java.io.FileOutputStream;
import org.jdom.Document;
import net.sf.json.JSON;
import net.sf.json.JSONSerializer;
import net.sf.json.xml.XMLSerializer;
public class JSON2XMLUtils {
/**
* 將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));
}
}