标签:style io ar color sp java for on bs
import java.util.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class Test {
public static void main(String[] args) {
//对象转json
Stu s = new Stu("123","1");
JSONObject jsonObject = JSONObject.fromObject(s);
System.out.println(jsonObject);//输出{"name":"123","age":"1"}
//当是数组或list的时候
Stu[] s2 = new Stu[5];
List<Stu> stuList = new ArrayList<Stu>();
for (int i = 0; i < s2.length; i++) {
s2[i] = new Stu();
s2[i].setAge(i+"age");
s2[i].setName(i+"name");
stuList.add(s2[i]);
}
JSONArray jsonArray = JSONArray.fromObject(s2);
System.out.println(jsonArray);
//当既有对象又有数组的时候
Map<String,Object> map = new HashMap<String,Object>();
Stu s3 = new Stu();
s3.setName("haha");
s3.setAge("23");
map.put("teacher", s3);
map.put("student", stuList);
JSONObject jsonObjectFromMap = JSONObject.fromObject(map);
System.out.println(jsonObjectFromMap);
//把json转化成对象
JSONObject obj=JSONObject.fromObject(s);
Stu emp=(Stu) JSONObject.toBean(obj,Stu.class);
System.out.println("12"+emp.getName());
//把json数组转化成对象
JSONArray a = JSONArray.fromObject(stuList);
Stu[] ss = (Stu[]) JSONArray.toArray(a,Stu.class);
for (Stu stu : ss) {
System.out.println(stu.getName());
}
}
}
标签:style io ar color sp java for on bs
原文地址:http://my.oschina.net/pzxzj/blog/346999