JSON格式和XML格式都是比較常見的資料存放區格式。但是有時候我們會從介面從伺服器或者其他途徑調用返回的結果並不是我們想要的。常見的就是我需要XML格式的,結果伺服器返回給我的是JSON格式。今天的常見問題就是,Java中JSON和XML如何互相轉換。
首先還是老規矩,上測試代碼:
import net.sf.json.JSONObject;import net.sf.json.xml.XMLSerializer;public class JSONToXml {private static final String STR_JSON = "{\"name\":\"Michael\",\"address\":{\"city\":\"shanghai\",\"street\":\" Changjiang Road \",\"postcode\":100025},\"blog\":\"http://cross.withiter.com\"}";public static String xml2JSON(String xml){return new XMLSerializer().read(xml).toString();}public static String json2XML(String json){JSONObject jobj = JSONObject.fromObject(json);String xml = new XMLSerializer().write(jobj);return xml;}public static void main(String[] args) {String xml = json2XML(STR_JSON);System.out.println("xml = "+xml);String json = xml2JSON(xml);System.out.println("json = "+json);}}
直接右擊run as java application,列印:
xml = <?xml version="1.0" encoding="UTF-8"?><o><address class="object"><city type="string">shanghai</city><postcode type="number">100025</postcode><street type="string"> Changjiang Road </street></address><blog type="string">http://cross.withiter.com</blog><name type="string">Michael</name></o>Dec 30, 2013 2:32:41 PM net.sf.json.xml.XMLSerializer getTypeINFO: Using default type stringjson = {"address":{"city":"shanghai","postcode":100025,"street":" Changjiang Road "},"blog":"http://cross.withiter.com","name":"Michael"}
我們可以看到兩種輸出格式。注意這裡用到的
XMLSerializer
和
JSONObject
很簡單對不對? Try it!