1.对象与字符串之间的互转
将对象转换成为字符串
String str = JSON.toJSONString(infoDo);
字符串转换成为对象
InfoDo infoDo = JSON.parseObject(strInfoDo, InfoDo.class);
2.对象集合与字符串之间的互转
将对象集合转换成为字符串
String users = JSON.toJSONString(users);
将字符串转换成为对象集合
List userList = JSON.parseArray(userStr, User.class);
3.字符串互转JSONObject
String 转 Json对象
JSONObject jsonObject = JSONObject.parseObject(jsonString);
json对象转string
JSONObject jsonObject = JSONObject.parseObject(str);//json对象转字符串
String jsonString = jsonObject.toJSONString();
4.map与字符串之间互转
//字符串转map
JSONObject jsonObject = JSONObject.parseObject(str);
Map<String,Object> map = (Map<String,Object>)jsonObject;// //json对象转Map
//map转字符串
String jsonString = JSON.toJSONString(map);
5.Map 转 Json对象
复制代码
//map转json对象
Map<String,Object> map = new HashMap<>();
map.put(“age”, 24);
map.put(“name”, “cool_summer_moon”);
JSONObject json = new JSONObject(map);
//json对象转Map
Map<String,Object> map = (Map<String,Object>)jsonObject;
6.list 转 json
List students = new ArrayList();
students.add(new Student(“xx”, 20));
students.add(new Student(“xxx”, 21));
String str = JSON.toJSONString(students); // List转json
System.out.println(str);
Map<String,Object> map = new HashMap<>();
map.put("a","b");
map.put("c","d");
System.err.println(map);//{a=b, c=d}
List<String> list = new ArrayList<>();
list.add("a");
list.add("b");
System.err.println(list); //[a, b]
map转换成字符串的方法
第一种:json-lib
依赖:
Map map = new HashMap();
map.put("sex", "男");
JSONObject jsonObject = JSONObject.fromObject(map);
//将json对象转化为json字符串
String result = jsonObject.toString();
第二种:alibaba的fastJson(推荐)
com.alibaba
fastjson
1.2.41
方法:
Map map = new HashMap();
map.put("sex", "男");
String result = JSONUtils.toJSONString(map);
第三种:google的gson
com.google.code.gson
gson
2.3.1
方法:
Map map = new HashMap();
map.put("sex", "男");
String result = new Gson().toJson(param).toString();
java对象和(fastjson)JSONObject相互转换
1.java对象转JSONObject
JSONObject json= (JSONObject) JSONObject.toJSON(javaBean);
2.JSONObject转java对象
User user= JSONObject.toJavaObject(json,User.class);
3.字符串转JSONObject
JSONObject json = JSON.parseObject(str);