当前位置: 代码迷 >> JavaScript >> Java - JSON转XML
  详细解决方案

Java - JSON转XML

热度:586   发布时间:2013-10-30 12:56:21.0
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 = <?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"}


  相关解决方案