JSON是什么

  • JSON 指的是 JavaScript 对象表示法(JavaScript Object Notation)
  • JSON 是轻量级的文本数据交换格式
  • JSON 独立于语言:虽然JSON 使用 JS语法来描述对象,但是独立于语言和平台。
  • JSON 解析器和 JSON 库支持不同的编程语言,(PHP,JSP,.NET,JAVA)等编程语言都支持JSON。
  • JSON 具有自我描述性,它比比XML 更小、更快,更易解析

常用方法

json字符串—>对象

// json字符串转换为JSONObject对象
JSONObject parseObject(String jsonString)
// json字符串转换为JSONArray对象
JSONArray parseArray(String jsonString)

// json字符串转换为javaBean
T parseObject(String jsonString, Class<T> clazz)
List<T> parseArray(String jsonString, Class<T> clazz)

对象—>json字符串

String toJSONString(Object object)

解析JSON字符串

{"112":{"name":"黄晓明","score":55},"113":{"name":"赵薇","score":63},"114":{"name":"陈坤","score":87},"115":{"name":"周迅","score":82}}

JSON格式:

{
	"112": {
		"name": "黄晓明",
		"score": 55
	},
	"113": {
		"name": "赵薇",
		"score": 63
	},
	"114": {
		"name": "陈坤",
		"score": 87
	},
	"115": {
		"name": "周迅",
		"score": 82
	}
}

首先要明白,以 { } 开头的是JSONObject,以 [ ] 开头的是JSONArray

@Test
    public void testJson01() {
        String  str = "{\"112\":{\"name\":\"黄晓明\",\"score\":55},\"113\":{\"name\":\"赵薇\",\"score\":63},\"114\":{\"name\":\"陈坤\",\"score\":87},\"115\":{\"name\":\"周迅\",\"score\":82}}";
        // 解析字符串,先将其转为JSONObject对象
        JSONObject jsonObject = JSONObject.parseObject(str);
        // 获取所有key的集合
        Set<String> keySet = jsonObject.keySet();
        Iterator<String> iterator = keySet.iterator();
        // 迭代遍历
        while (iterator.hasNext()){
            JSONObject jb = jsonObject.getJSONObject(iterator.next());
            System.out.print(jb.getString("name"));
            System.out.println(jb.getInteger("score"));
        }
    }

运行结果:

android fastjson转的字符串添加转义 fastjson字符串转对象_java

解析JSON数组

[{"name":"Java","pId":100},{"name":"Spring框架","pId":888},{"name":"MySQL数据库","pId":999}]

JSON格式:

[
    {
        "name": "Java", 
        "pId": 100
    }, 
    {
        "name": "Spring框架", 
        "pId": 888
    }, 
    {
        "name": "MySQL数据库", 
        "pId": 999
    }
]

Java代码实现:

@Test
    public void testJson02() {
        String  str = "[{\"name\":\"Java\",\"pId\":100},{\"name\":\"Spring框架\",\"pId\":888},{\"name\":\"MySQL数据库\",\"pId\":999}]";
        // 解析字符串,将其转为JSONArray对象
        JSONArray array = JSONObject.parseArray(str);
        /*ListIterator<Object> iterator = array.listIterator();*/
        //迭代遍历方式A
        for (int i = 0; i < array .size(); i++) {
              JSONObject jb = array .getJSONObject(i);
              System.out.println(jb.getString("name"));
              System.out.println(jb.getString("pId"));
        }
        //迭代遍历方式B
        for (Object o : array ) {
              JSONObject s =  (JSONObject)o;
              System.out.println(s.getString("name"));
              System.out.println(s.getString("pId"));
        }
    }

运行结果:

android fastjson转的字符串添加转义 fastjson字符串转对象_mysql_02

要解析的JSON字符串

{
	"errcode": 0,
	"errmsg": "ok",
	"result": {
		"auto_add_user": true,
		"dept_id": 35,
		"dept_permits": [],
		"extention": "{\"faceCount\":\"657\"}",
		"hide_dept": false,
		"name": "layman",
		"user_permits": []
	},
	"request_id": "iyptirsmnxy5"
}

解析复杂Json字符串

{'teacherName':'crystall','teacherAge':27,'course':{'courseName':'english','code':1270},'students':[{'studentName':'lily','studentAge':12},{'studentName':'lucy','studentAge':15}]}

Json格式:

{
    "teacherName": "crystall", 
    "teacherAge": 27, 
    "course": {
        "courseName": "english", 
        "code": 1270
    }, 
    "students": [
        {
            "studentName": "lily", 
            "studentAge": 12
        }, 
        {
            "studentName": "lucy", 
            "studentAge": 15
        }
    ]
}

java代码:

@Test
    public void testJson03() {
        String  str = "{'teacherName':'layman','teacherAge':27,'course':{'courseName':'english','code':1270},'students':[{'studentName':'lily','studentAge':12},{'studentName':'lucy','studentAge':15}]}";
        
        JSONObject jb = JSONObject.parseObject(str);
        String teacherName = jb.getString("teacherName");
        Integer teacherAge = jb.getInteger("teacherAge");
        JSONObject course = jb.getJSONObject("course");
        JSONArray students = jb.getJSONArray("students");

        System.out.println(teacherName);
        System.out.println(teacherAge);
        System.out.println(course);
        System.out.println(students);
    }

把Json字符串直接转化为对象

以上面的复杂字符串为例子

{'teacherName':'crystall','teacherAge':27,'course':{'courseName':'english','code':1270},'students':[{'studentName':'lily','studentAge':12},{'studentName':'lucy','studentAge':15}]}

新建实体类teacher :

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

import java.util.List;

@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class Teacher{

    private String teacherName;
    private Integer age;
    private Course course;
    private List<Student> Student;
}

新建实体类Student

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class Student {
    @JSONField(name = "studentName")
    private String studentName;
    @JSONField(name = "studentAge")
    private Integer studentAge;
}

新建实体类Course

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class Course {
    private String name;
    private Integer code;
}

转换方法:

@Test
    public void testJson04() {
        String  str = "{'teacherName':'layman','teacherAge':27,'course':{'courseName':'english','code':1270},'students':[{'studentName':'lily','studentAge':12},{'studentName':'lucy','studentAge':15}]}";
        // 解析字符串,将其转为JSONArray对象
        Teacher teacher = JSON.parseObject(str, Teacher.class);
        System.out.println(teacher);
    }

运行结果:

android fastjson转的字符串添加转义 fastjson字符串转对象_spring_03


可以看到,除了teacher中的teacherName属性有值外,其它的属性都没有值。

因为Json是根据key值去匹配变量名,如果变量名和key值不同,就会出现匹配不上,从而出现null值。

如何解决这个问题:

  • key值和变量名一一对应
  • 变量名上添加JSONField注解

进行teacher类的改造:

import com.alibaba.fastjson.annotation.JSONField;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import java.util.List;

@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class Teacher{

    @JSONField(name = "teacherAge")
    private String name;
    @JSONField(name = "teacherAge")
    private Integer age;
    private Course course;
    private List<Student> Student;
}

改造Course类:

import com.alibaba.fastjson.annotation.JSONField;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class Course {
    @JSONField(name = "courseName")
    private String name;
    private Integer code;
}

重新运行,如下:

android fastjson转的字符串添加转义 fastjson字符串转对象_mysql_04

可以看到,Student这个类依然没有获取到。

为什么呢?

因为Json字符串中的key是:

students

而,Teacher类中的Field是

private List student;

students 和 List student并不匹配,少了个s

  • tips:Field和key的值需要一一对应(不区分大小写)
如何解决

在student添加注解

@JSONField(name = "students")
    private List<Student> student;
修改后运行结果

android fastjson转的字符串添加转义 fastjson字符串转对象_JSON_05