XML转JSON

XML转JSON

Step 1 : 下载 java-json.jar

http://www.java2s.com/Code/JarDownload/java/java-json.jar.zip

Step 2: 增加 java-json.jar 到/libs目录并add to build path.

Step 3: 测试demo

package test;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.XML;

public class Test {
	public static String signData = "<?xml version="1.0" encoding="utf-8"?><BodSignData version="1.0"><Field><Name>orderId</Name><DispName></DispName><Value>5001</Value></Field><Field><Name>payAccountNo</Name><DispName>kevin</DispName><Value>590000113004775</Value></Field><Field><Name>amount</Name><DispName>undefined</DispName><Value>520</Value></Field><Field><Name>masterName</Name><DispName>undefined</DispName><Value>sn</Value></Field><Field><Name>payDate</Name><DispName>undefined</DispName><Value>20150704</Value></Field></BodSignData>";
	
	public static void main(String[] args) {
		/*JSONObject jsonObj = null;
		try {
			jsonObj = XML.toJSONObject(signData);
			JSONObject jsonBodSignData = jsonObj.getJSONObject("BodSignData");
			System.err.println(jsonBodSignData.toString());
			JSONArray jsonField=jsonBodSignData.getJSONArray("Field");
			System.err.println(jsonField);
			for (int i = 0; i < jsonField.length(); i++) {
				System.err.println(jsonField.get(i));
			}
		} catch (JSONException e) {
			e.printStackTrace();
		} 
		Log.e("XML", signData);
		Log.e("JSON", jsonObj.toString());
		//System.err.println(signData);
		//System.err.println(jsonObj.toString());
*/		
		String resp="<?xml version="1.0" encoding="utf-8"?><request><filelist><treenode><!--code 0表示成功--><code>0</code></treenode></filelist></request>";
		try {
			JSONObject jsonObj = XML.toJSONObject(resp);
			JSONObject jsonRequest = jsonObj.getJSONObject("request");
			JSONObject jsonfilelist=jsonRequest.getJSONObject("filelist");
			JSONObject jsontreenode=jsonfilelist.getJSONObject("treenode");
			int jsoncode=jsontreenode.getInt("code");
			System.err.println(jsoncode);
		} catch (JSONException e) {
			e.printStackTrace();
		} 
		
	}
}