JSONObject本质是一个Map
JSONArray本质是一个List
1.java对象转JSON
String str = JSON.toJSONString(javaBean);
2.JSON转java对象
User user = JSON.parseObject(str,Entity.class);
3.List转JSON
String str = JSON.toJSONString(list)
4.JSON转List
List list = JSON.parseArray(str,Entity.class)
5.数组转JSON
String str = JSON.toJSONString(array)
举例:
String[] initArray = {"Jack","Lili","Lucy"};
String str= JSON.toJSONString(initArray);
System.out.println(str);
console:
["Jack","Lili","Lucy"]
6. java对象转JSONObject
JSONObject json= (JSONObject) JSONObject.toJSON(javaBean);
7. JSONObject转java对象
User user= JSONObject.toJavaObject(json,User.class);
8. 字符串转JSONObject
JSONObject json = JSON.parseObject(str);
9.JSONObject转字符串
String str= JSONObject.toJSONString(resultData);
10.JSONArray转list
JSONObject ObjOne = new JSONObject();
JObjOne.put("name", "Tom");
JSONObject ObjTwo = new JSONObject();
ObjTwo.put("sex", "男");
JSONObject ObjThree = new JSONObject();
ObjThree.put("age", 10);
JSONArray jsonArray = new JSONArray();
jsonArray.add(ObjOne);
jsonArray.add(ObjTwo);
jsonArray.add(ObjThree);
List<User> list = jsonArray.toJavaList(User.class);
System.out.println(list);
Console:
[User(name=Tom, sex=null, age=null), User(name=null, sex=男, age=null), User(name=null, sex=null, age=10)]