使用目的
目前数据交互大多以 JSON 字符串为信息传输,主要格式有
{"age":"22","name":"李四"}
[{"age":"21","name":"张三"}]
最常见的应用场景是前后端对接,第三方平台文档对接,下面展示转换使用。
一、引入 jar , 此处引入 com.alibaba.fastjson 版本的jar包
-
-
<groupId>com.alibaba</groupId>
-
<artifactId>fastjson</artifactId>
-
<version>1.1.31</version>
-
二、建立测试类对象
-
-
-
-
-
public String getName() {
-
-
-
-
public void setName(String name) {
-
-
-
-
-
-
-
-
public void setAge(String age) {
-
-
-
-
三、转换
1、对象 转 JSON
-
Student stu1 = new Student();
-
-
-
-
String stu1Json = JSONObject.toJSONString(stu1);
输出:
{"age":"21","name":"张三"}
2、JSON 转 对象
-
Student stu1to = JSON.parseObject(stu1Json, Student.class);
-
System.out.println("json 转对象:");
-
System.out.println(stu1to);
-
System.out.println(stu1to.getName());
-
System.out.println(stu1to.getAge());
输出:
-
-
-
-
注:JSON键名要与对象属性名相对应
3、对象数组 转 JSON
-
Student stu2 = new Student();
-
-
-
List<Student> list = new ArrayList<Student>();
-
-
-
-
String listJson = JSONObject.toJSONString(list);
-
System.out.println(listJson);
输出:
[{"age":"21","name":"张三"},{"age":"22","name":"李四"}]
4、JSON 转 对象数组
-
List<Student> studentList = JSON.parseArray(listJson, Student.class);
-
for (Student student : studentList) {
-
System.out.println(student.getName());
-
输出:
-
-
-
5、JSON多级组合,适用于请求文档传输参数
-
JSONObject jsona = new JSONObject();
-
jsona.put("number", "1");
-
JSONObject jsonb = new JSONObject();
-
jsonb.put("listMap", list);
-
-
JSONObject jsonAll = new JSONObject();
-
jsonAll.put("jsona", jsona);
-
jsonAll.put("jsonb", jsonb);
-
String jsonAllStr =JSONObject.toJSONString(jsonAll);
-
System.out.println(jsonAllStr);
输出:
{"jsona":{"number":"1"},"jsonb":{"listMap":[{"age":"21","name":"张三"},{"age":"22","name":"李四"}]}}
6、多级 JSON 组合
6.1、只获取指定字段,接上方示例代码
-
String getJsona = JSON.parseObject(jsonAllStr).getString("jsona");
-
String strjsona = JSON.parseObject(getJsona, String.class);
-
System.out.println("只拿jsona信息");
-
System.out.println(strjsona);
输出:
-
-
6.2、获取指定字段对象
-
String getJsonb = JSON.parseObject(jsonAllStr).getString("jsonb");
-
String getJsonbb = JSON.parseObject(getJsonb).getString("listMap");
-
List<Student> strjsonb = JSON.parseArray(getJsonbb, Student.class);
-
System.out.println("只拿jsonbb信息");
-
System.out.println(strjsonb);
输出:
-
-
[Student@3d04a311, Student@7a46a697]
-