json lib

public class Test {
	public static void main(String[] args) {

		// 转化数组,集合
		// 1.
		boolean[] boolArray = new boolean[] { true, false, true };
		JSONArray jsonArray1 = JSONArray.fromObject(boolArray);
		System.out.println(jsonArray1);
		/* [true,false,true] */

		// 2.
		List<String> list = new ArrayList<String>();
		list.add("第一个");
		list.add("第二个");
		JSONArray jsonArray2 = JSONArray.fromObject(list);
		System.out.println(jsonArray2);
		/* ["第一个","第二个"] */

		// 3.
		JSONArray jsonArray3 = JSONArray.fromObject("['json','is','easy']");
		System.out.println(jsonArray3);
		/* ["json","is","easy"] */

		// 转化对象,转化Map
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("name", "json");
		map.put("bool", Boolean.TRUE);
		map.put("int", new Integer(1));
		map.put("arr", new String[] { "a", "b" });
		map.put("func", "function(i){return this.arr[i];}");
		JSONObject json = JSONObject.fromObject(map);
		System.out.println(json);
		/*
		 * {"func":function(i){return
		 * this.arr[i];},"arr":["a","b"],"int":1,"bool":true,"name":"json"}
		 */

		// 转化Bean
		Stock stock = new Stock();
		stock.setId("000001");
		stock.setName("浦发银行");
		JSONObject jsonObject = JSONObject.fromObject(stock);
		System.out.println(jsonObject);
		/* {"id":"000001","name":"浦发银行","now":0,"today":0,"yesterday":0} */

		// 从JSON到Beans//转化为动态bean
		String myjson = "{name:\"json\",bool:true,int:1,double:2.2,function:function(a){return a;},array:[1,2]}";
		JSONObject jsonObj = JSONObject.fromObject(myjson);
		Object bean = JSONObject.toBean(jsonObj);
		System.out.println(bean);
		/*
		 * net.sf.ezmorph.bean.MorphDynaBean@16df84b[ {double=2.2, int=1,
		 * function=function(a){ return a; }, name=json, bool=true, array=[1,
		 * 2]} ]
		 */

		JSONObject json1 = new JSONObject(true);
		XMLSerializer xmlSerializer2 = new XMLSerializer();
		String xml = xmlSerializer2.write(json1);
		System.out.println("xml:" + xml);
		/*
		 * xml:<?xml version="1.0" encoding="UTF-8"?> <o null="true"/>
		 */
		JSONObject json2 = JSONObject
				.fromObject("{\"name\":\"json\",\"bool\":true,\"int\":1}");
		XMLSerializer xmlSerializer3 = new XMLSerializer();
		String xml2 = xmlSerializer3.write(json2);
		System.out.println("xml2:" + xml2);
		/*
		 * xml2:<?xml version="1.0" encoding="UTF-8"?> <o><bool
		 * type="boolean">true</bool><int type="number">1</int><name
		 * type="string">json</name></o>
		 */
		JSONArray json3 = JSONArray.fromObject("[1,2,3]");
		XMLSerializer xmlSerializer4 = new XMLSerializer();
		String xml3 = xmlSerializer4.write(json3);
		System.out.println("xml3:" + xml3);
		/*
		 * xml3:<?xml version="1.0" encoding="UTF-8"?> <a><e type="number">1</e><e
		 * type="number">2</e><e type="number">3</e></a>
		 */
	}
}

你可能感兴趣的:(xml,json,bean,.net)