Json转化
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());
}
}
}
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。