日期:2014-05-16 浏览次数:20332 次
前几天在论坛上回答问题的代码,写下来记录下:
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); } }
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>
Oct 29, 2013 2:16:27 PM net.sf.json.xml.XMLSerializer getType
INFO: Using default type string
json={"address":{"city":"shanghai","postcode":100025,"street":" Changjiang Road "},"blog":"http://cross.withiter.com","name":"Michael"}