1. 程式人生 > >Json 與 XML 的互相轉換

Json 與 XML 的互相轉換

net.sf.json.xml.XMLSerializer

private static String json2Xml(JSONObject json,String rootName){
		String sXml="";
		XMLSerializer xmlSerializer = new XMLSerializer();				
		xmlSerializer.setTypeHintsEnabled( false );       
		xmlSerializer.setRootName(rootName); 
		String sContent=xmlSerializer.write(json);
		try {
			Document docCon = DocumentHelper.parseText(sContent);					
			sXml=docCon.getRootElement().asXML();
			//System.out.println(sXml);

		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return sXml;
	}
	
	public String xml2Json(String xmlString){
		  XMLSerializer xmlSerializer = new XMLSerializer();
		  //xmlSerializer.setRootName("result" );
		  JSON json = xmlSerializer.read(xmlString);		 
		  return json.toString(1);
	}