标签:
package com.chauvet.utils;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class JsonHelper{
public static void main(String[] args) {
JSONObject jsonObject = object2Json();
System.out.println(jsonObject.toString());
JSONArray jsonArray = List2Json();
System.out.println(jsonArray.toString());
jsonObject2object(jsonObject);
JsonArray2List(jsonArray);
}
/***
* 对象转成JSONObject
* @return
*/
public static JSONObject object2Json(){
Student s1 = new Student();
s1.setId("1");
s1.setName("1");
/**
* java对象转换成json对象,并获取json对象属性
*/
JSONObject jsonStu = JSONObject.fromObject(s1);
return jsonStu;
}
/***
* list转JSONArray
* @return
*/
public static JSONArray List2Json(){
Student s1 = new Student();
s1.setId("1");
s1.setName("1");
Student s2 = new Student();
s2.setId("2");
s2.setName("2");
Student s3 = new Student();
s3.setId("3");
s3.setName("3");
List<Student> stuList = new ArrayList<Student>();
stuList.add(s1);
stuList.add(s2);
stuList.add(s3);
/**
* List转换成json
*/
JSONArray jsonArray = JSONArray.fromObject(stuList);
return jsonArray;
}
/***
* JSONObject转对象
* @param jsonStr
*/
public static void jsonObject2object(JSONObject jsonStr){
/**
* json对象转换成java对象,并获取java对象属性
*/
Student stu = (Student) JSONObject.toBean(jsonStr, Student.class);
System.out.println(stu.getId());
System.out.println(stu.getName());
}
/***
* JSONArray 转 List
* @param jsonArray
*/
public static void JsonArray2List(JSONArray jsonArray){
Collection<?> c = JSONArray.toCollection(jsonArray);
Iterator<?> it=c.iterator();
while (it.hasNext()) {
JSONObject jsonObj=JSONObject.fromObject(it.next());
Student stu=(Student) JSONObject.toBean(jsonObj,Student.class);
System.out.println(stu.getId());
System.out.println(stu.getName());
}
}
}
标签:
原文地址:http://www.cnblogs.com/chauvet/p/5754203.html