json转换,对象转json字符串或json字符串转对象

3/3/2017来源:C/C++教程人气:2427

采用两种方式json对象的转换 
com.alibaba和
net.sf.json-lib
依赖的maven
<dependency>
   <groupId>com.alibaba</groupId>
   <artifactId>fastjson</artifactId>
   <version>1.2.24</version>
</dependency>
<dependency>
   <groupId>net.sf.json-lib</groupId>
   <artifactId>json-lib</artifactId>
   <version>2.4</version>
   <classifier>jdk15</classifier>
</dependency>
String json = "{\"name\":\"lil\",\"age\":\"12\",\"address\":'北京',\"obj\":{\"phone\":123131,\"dd\":\"hh\"}}";

//net.sf.json方式解析json字符串
JSONObject jsonObject = JSONObject.fromObject(json);
//直接获取对象name属性
String value = jsonObject.getString("name");
 //jsonObject中的对象调用对象中的属性 如:json字符串对象中包含obj对象
 jsonObject.getJSONObject("obj").get("phone");

//com.alibaba方式解析json字符串
com.alibaba.fastjson.JSONObject object = com.alibaba.fastjson.JSONObject.parSEObject(json);
object.getJSONObject("obj").getString("phone");
value = object.getString("age");


//将对象转换为json字符串
Person person = new Person();
person.setName("lis");
person.setAge(13);
person.setAddress("beijing");
String perStr = com.alibaba.fastjson.JSONObject.toJSONString(person);

object = com.alibaba.fastjson.JSONObject.parseObject(perStr);
//获取Person对象中的address属性
value = object.getString("address");

List list = Arrays.asList(1, 2, 3);
int[] arr = new int[]{3,2,12};
//Class<T>指定返回的类型
List neList = com.alibaba.fastjson.JSONObject.parseObject(com.alibaba.fastjson.JSONObject.toJSONString(list), List.class);
//首先将对象转换为字符串 JSONObject.toJSONString
List<Integer> neArr = (List<Integer>)com.alibaba.fastjson.JSONObject.parseArray(com.alibaba.fastjson.JSONObject.toJSONString(arr),Integer.class);