本工程代码已上传至资源,如有需要,请自行下载。
package com.michael; import static org.junit.Assert.assertEquals; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.apache.commons.beanutils.PropertyUtils; import org.junit.Test; public class JsonLibTest { /** * 将数组转换为json对象 */ // @Test public void testArrayToJSON() { boolean[] boolArray = new boolean[] { true, false, true }; JSONArray jsonArray = JSONArray.fromObject(boolArray); System.out.println("testArrayToJSON----jsonArray-----" + jsonArray); } /** * 将集合转换为json */ // @Test public void testListToJSON() { List<String> list = new ArrayList<String>(); list.add("first"); list.add("second"); JSONArray jsonArray = JSONArray.fromObject(list); System.out.println("testListToJSON---jsonArray----" + jsonArray); } /** * 将json字符串转换为json对象 */ @Test public void testJsonStrToJSON() { JSONArray jsonArray = JSONArray.fromObject("['json','is','easy']"); System.out.println("testJsonStrToJSON---jsonArray----" + jsonArray); } /** * 将map转换为json对象 */ @Test public void testMapToJSON() { 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 jsonObject = JSONObject.fromObject(map); System.out.println("testJsonStrToJSON---jsonObject----" + jsonObject); } // 将实体类转换为json @Test public void testBeadToJSON() { Car bean = new Car(); bean.setId("001"); bean.setName("hello"); bean.setDate(new Date()); List<Car> cars = new ArrayList<Car>(); cars.add(new Car("AUDI")); cars.add(new Car("BMW")); cars.add(new Car("QQ")); // cars.add(new Person("test")); bean.setCars(cars); JSONObject jsonObject = JSONObject.fromObject(bean); System.out.println("testBeadToJSON---jsonObject----" + jsonObject); } @Test /** * 将json字符串转换为对象 * @throws Exception */ public void testJSONToObject() throws Exception { String json = "{name=\"json\",bool:true,int:1,double:2.2,func:function(a){ return a; },array:[1,2]}"; JSONObject jsonObject = JSONObject.fromObject(json); Object bean = JSONObject.toBean(jsonObject); assertEquals(jsonObject.get("name"), PropertyUtils.getProperty(bean, "name")); assertEquals(jsonObject.get("bool"), PropertyUtils.getProperty(bean, "bool")); assertEquals(jsonObject.get("int"), PropertyUtils.getProperty(bean, "int")); assertEquals(jsonObject.get("double"), PropertyUtils.getProperty(bean, "double")); assertEquals(jsonObject.get("func"), PropertyUtils.getProperty(bean, "func")); List arrayList = (List) JSONArray.toCollection(jsonObject .getJSONArray("array")); for (Object object : arrayList) { System.out.println(object); } } }
Java 处理json常用代码,布布扣,bubuko.com
原文地址:http://blog.csdn.net/michael10001/article/details/31453061