获取方式
- maven 引入依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.73</version>
</dependency>
- 直接下载
https://search.maven.org/remote_content?g=com.alibaba&a=fastjson&v=LATEST
常用转换
对象转 map,map 转对象
Stuent student = new Student();
student.setName("野比大雄");
//Object转Map
Map map = JSONObject.parseObject(JSONObject.toJSONString(student), Map.class);
Map<String,Object> map = JSONObject.parseObject(JSON.toJSONString(student));
//Map转Object
Stuent student1 = JSON.parseObject(JSON.toJSONString(map), Stuent.class);
Stuent student2 = JSONObject.toJavaObject(JSON.toJSONString(map), Stuent.class);
map 转 JSON,JSON 转 Map
// map 转 json
Map<String, Object> map = new HashMap<String, Object>();
map.put("a", "a");
map.put("b", "123");
JSONObject json = new JSONObject(map);
// json 转 map
JSONObject json = new JSONObject();
json.put("ccc", "321");
json.put("bbb", "123");
Map<String, Object> map = (Map<String, Object>)json;
map 转 string
Map<String, Object> map = new HashMap<>();
map.put("a", "b");
String s = JSONObject.toJSONString(map);
JSON 转 String,String 转 JSON
// json 转 string
JSONObject json = new JSONObject();
json.put("c", "v");
json.put("z", "123n);
String str = json.toJSONString();
// String 转 json
String str = "{\"username\":\"dsad\",\"qwewqe\":\"123\"}";
JSONObject json = JSONObject.parseObject(str);
对象 转 String,String 转对象
// 对象转 string
String str = JSON.toJSONString(student);
// string 转 对象
Student student = JSON.parseObject(str, Student.class);
对象集合 转 string, string 转 对象集合
// 对象集合 转 string
List<Student> studentList = new ArrayList<>();
Student s = new Student();
s.setName("静香");
studentList.add(s);
String students = JSON.toJSONString(studentList);
// 字符串转换成为对象集合
List<Student> studentList = JSON.parseArray(students, Student.class);