JSON和XML格式互相转换

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 );
}
}
 
   
xml =
shanghai100025 Changjiang Road
http://cross.withiter.comMichael
Dec 30, 2013 2:32:41 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"}

你可能感兴趣的:(JSON和XML格式互相转换)