bean与json互转
public static void main(String[] args) {
//定义对象
Student stu = new Student("张三", "123456");
//JavaBean对象转json字符串
JSONObject jsonObject = JSONObject.fromObject(stu);
System.out.println(jsonObject);
//json字符串转为javaBean
//定义json字符串
String jsondata = "{\"username\":\"李四\", \"password\":\"123\"}";
//转为json对象
JSONObject json = JSONObject.fromObject(jsondata);
//转为JavaBean对象,强转
Student stu2 = (Student)JSONObject.toBean(json, Student.class);
System.out.println(stu2.toString());
}
//list与json互转
public static void main(String[] args) {
//定义list集合
List list = new ArrayList();
list.add(new Student("张三", "123"));
list.add(new Student("李四", "456"));
//list转json字符串
JSONArray jsonArray = JSONArray.fromObject(list);
System.out.println(jsonArray);
//json字符串转list
List list2 = new ArrayList();
String jsondata = "[{\"password\":\"123\",\"username\":\"张三\"},{\"password\":\"456\",\"username\":\"李四\"}]";
JSONArray jsonArray1 = JSONArray.fromObject(jsondata);
for(int i = 0; i < jsonArray1.size(); i++) {
JSONObject jsonObject2 = jsonArray1.getJSONObject(i);
Student stu2 = (Student)JSONObject.toBean(jsonObject2, Student.class);
list2.add(stu2);
}
System.out.println(list2);
}
//map与json互转
public static void main(String[] args) {
//定义map集合
Map map = new HashMap();
map.put("1", new Student("张三", "123"));
map.put("2", new Student("李四", "456"));
//Map转json字符串
JSONObject jsonMap = JSONObject.fromObject(map);
System.out.println(jsonMap);
//定义字符串map集合
String jsondata = "{\"1\":{\"password\":\"123\",\"username\":\"张三\"},\"2\":{\"password\":\"456\",\"username\":\"李四\"}}";
//map集合字符串转为map
Map map2 = (Map)JSONObject.fromObject(jsondata);
Set set = map2.keySet();
//定义迭代器,迭代输出
Iterator ite = set.iterator();
while(ite.hasNext()) {
//取出一个字符串对象
String key = (String)ite.next();
//转为json格式
JSONObject jsonObject = JSONObject.fromObject(map2.get(key));
//转为对象
Student stu = (Student)JSONObject.toBean(jsonObject, Student.class);
System.out.println(key+" "+stu);
}
}
deepBean与json互转
// deepBean与json互转
String jsondata = "{\"student\":{\"username\":\"李四\", \"password\":\"123\"},\"count\":20,\"name\":\"这是我的班级名\"}";
//转为json对象
JSONObject json = JSONObject.fromObject(jsondata);
System.out.println("json = " + json);
//转为JavaBean对象,强转
Grade grade = (Grade)JSONObject.toBean(json, Grade.class);
//bean转json
JSONObject grade11 = JSONObject.fromObject(grade);
System.out.println(grade11);