Json格式数据使用总结

目录

 

简介

Json格式数据形式和语法

使用FastJson解析数据

使用JackJson解析数据

前端js解析json数据

 


简介

Json是一种数据格式,采用key:value的文本格式存储和表示数据

Json格式数据形式和语法

  1. json对象
    {
    ​
        "ID": 1001,
    ​
        "name": "张三",
    ​
    }
    /*
    特点:
    数据在花括号中数据以"键:值"对的形式出现(其中键多以字符串形式出现,值可取字符串,数值,甚至其他json对象)
    每两个"键:值"对以逗号分隔(最后一个"键:值"对省略逗号)
    */
  2. json对象数组
    {
    ​
        "部门名称":"研发部",
    ​
        "部门成员":[
    ​
        {"ID": 1001, "name": "张三", "age": 24},
    ​
        {"ID": 1002, "name": "李四", "age": 25},
    ​
        {"ID": 1003, "name": "王五", "age": 22}],
    ​
        "部门位置":"xx楼21号"
    ​
    }
  3. json字符串

    JSON字符串也是在平时开发中使用较多的,json字符串应满足以下条件:

    1:它必须是一个字符串,由" "或者' '包裹数据,支持字符串的各种操作

    2:里面的数据格式应该要满足其中一个格式,可以是json对象,也可以是json对象数组或者是两种基本形式的组合变形。

使用FastJson解析数据

1.语法

在fastjson包中主要有3个类,JSON,JSONArray,JSONObject

三者之间的关系如下,JSONObject和JSONArray继承JSON

联系上面讲到的json基础知识并对应这三个类,可以发现,JSONObject代表json对象,JSONArray代表json对象数组,JSON代表JSONObject和JSONArray的转化。

JSONObject类使用

JSONObject实现了Map接口,而json对象中的数据都是以"键:值"对形式出现, JSONObject底层操作是由Map实现的。类中主要是get()方法。JSONObject相当于json对象,该类中主要封装了各种get方法,通过"键:值"对中的键来获取其对应的值。

JSONArray类使用

JSONArray的内部是通过List接口中的方法来完成操作的。JSONArray代表json对象数组,json数组对象中存储的是一个个json对象,所以类中的方法主要用于直接操作json对象。比如其中的add(),remove(),containsAll()方法,对应于json对象的添加,删除与判断。 其内部主要由List接口中的对应方法来实现。

跟JSONObject一样,JSONArray里面也有一些get()方法,不过不常用,最有用的应该是getJSONObject(int index)方法,该方法用于获取json对象数组中指定位置的JSONObject对象,配合size()方法,可用于遍历json对象数组中的各个对象。 通过以上两个方法,在配合for循环,即可实现json对象数组的遍历。此外JSONArray中也实现了迭代器方法来遍历。 通过遍历得到JSONObject对象,然后再利用JSONObject类中的get()方法,即可实现最终json数据的获取。

JSON类使用

JSON类主要是实现转化用的,最后的数据获取,还是要通过JSONObject和JSONArray来实现。类中的主要是实现json对象,json对象数组,javabean对象,json字符串之间的相互转化。

2.使用

json字符串—》JSONObject

 

用JSON.parseObject()方法即可将JSon字符串转化为JSON对象,利用JSONObject中的get()方法来获取JSONObject中的相对应的键对应的值

//json格式数据---对象类型
String  JSON_OBJ_STR = "{\"studentName\":\"lily\",\"studentAge\":12}";
JSONObject jsonObject = JSON.parseObject(JSON_OBJ_STR);
System.out.println("StudentName: " + jsonObject.getString("studentName") + "," + "StudentAge: " + jsonObject.getInteger("studentAge"));

JSONObject—》json字符串

用JSON.toJSONString()方法即可将JSON对象转化为JSON字符串

JSON字符串数组—》JSONArray

将JSON字符串数组转化为JSONArray,通过JSON的parseArray()方法。JSONArray本质上还是一个数组,对其进行遍历取得其中的JSONObject,然后再利用JSONObject的get()方法取得其中的值。有两种方式进行遍历

方式一:通过jsonArray.size()获取JSONArray中元素的个数,再通过getJSONObject(index)获取相应位置的JSONObject,循环变量取得JSONArray中的JSONObject,再利用JSONObject的get()进行取值。

方式二:通过jsonArray.iterator()获取迭代器

JSON_ARRAY_STR = "     [{\"studentName\":\"lily\",\"studentAge\":12}," +
            "{\"studentName\":\"lucy\",\"studentAge\":15}]";
JSONArray jsonArray = JSON.parseArray(JSON_ARRAY_STR);
// 遍历方式一
//        int size = jsonArray.size();
//        for(int i = 0;i < size;i++){
//            JSONObject jsonObject = jsonArray.getJSONObject(i);
//            System.out.println("studentName: " + jsonObject.getString("studentName") + ",StudentAge: " + jsonObject.getInteger("studentAge"));
//        }
// 遍历方式二
        Iterator<Object> iterator = jsonArray.iterator();
        while (iterator.hasNext()){
            JSONObject jsonObject = (JSONObject) iterator.next();
            System.out.println("studentName: " + jsonObject.getString("studentName") + ",StudentAge: " + jsonObject.getInteger("studentAge"));
        }

 

JSONArray—》json字符串

用JSON.toJSONString()方法即可将JSONArray转化为JSON字符串

json字符串—》JavaBean

String  JSON_OBJ_STR = "{\"studentName\":\"lily\",\"studentAge\":12}";
// 第一种方式
        JSONObject jsonObject = JSON.parseObject(JSON_OBJ_STR);
        String studentName = jsonObject.getString("studentName");
        Integer studentAge = jsonObject.getInteger("studentAge");
        Student student = new Student(studentName, studentAge);
// 第二种方式,//第二种方式,使用TypeReference<T>类,由于其构造方法使用protected进行修饰,故创建其子类
        Student student1 = JSON.parseObject(JSON_OBJ_STR, new TypeReference<Student>() {});
// 第三种方式,通过反射,建议这种方式
        Student student2 = JSON.parseObject(JSON_OBJ_STR, Student.class);

JavaBean —》json字符串

也是通过JSON的toJSONString,不管是JSONObject、JSONArray还是JavaBean转为为JSON字符串都是通过JSON的toJSONString方法。

Student lily = new Student("lily", 12);
String s = JSON.toJSONString(lily);

json字符串数组—》JavaBean-List

JSON_ARRAY_STR = "     [{\"studentName\":\"lily\",\"studentAge\":12}," +
            "{\"studentName\":\"lucy\",\"studentAge\":15}]";
// 方式一:
        JSONArray jsonArray = JSON.parseArray(JSON_ARRAY_STR);
        //遍历JSONArray
        List<Student> students = new ArrayList<Student>();
        Iterator<Object> iterator = jsonArray.iterator();
        while (iterator.hasNext()){
            JSONObject next = (JSONObject) iterator.next();
            String studentName = next.getString("studentName");
            Integer studentAge = next.getInteger("studentAge");
            Student student = new Student(studentName, studentAge);
            students.add(student);
        }
        // 方式二,使用TypeReference<T>类,由于其构造方法使用protected进行修饰,故创建其子类
        List<Student> studentList = JSON.parseObject(JSON_ARRAY_STR,new TypeReference<ArrayList<Student>>() {});
        // 方式三,使用反射
        List<Student> students1 = JSON.parseArray(JSON_ARRAY_STR, Student.class);
        System.out.println(students1);

 JavaBean-List —》json字符串数组

JavaBean_List到json字符串-数组类型的转换,直接调用JSON.toJSONString()方法即可

复杂嵌套json格式字符串—》JavaBean_obj

对于复杂嵌套的JSON格式,利用JavaBean进行转换的时候要注意:

有几个JSONObject就定义几个JavaBean

内层的JSONObject对应的JavaBean作为外层JSONObject对应的JavaBean的一个属性

public class Student {
    private String studentName;
    private int studentAge;
​
    public Student() {
    }
​
    public Student(String studentName, int studentAge) {
        this.studentName = studentName;
        this.studentAge = studentAge;
    }
​
    public String getStudentName() {
        return studentName;
    }
​
    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }
​
    public int getStudentAge() {
        return studentAge;
    }
​
    public void setStudentAge(int studentAge) {
        this.studentAge = studentAge;
    }
​
    @Override
    public String toString() {
        return "Student{" +
                "studentName='" + studentName + '\'' +
                ", studentAge=" + studentAge +
                '}';
    }
}
​


​
import java.util.List;
​
public class Teacher {
    private String teacherName;
    private int teacherAge;
    private Course course;
    private List<Student> students;
​
    public Teacher() {
    }
​
    public Teacher(String teacherName, int teacherAge, Course course, List<Student> students) {
        this.teacherName = teacherName;
        this.teacherAge = teacherAge;
        this.course = course;
        this.students = students;
    }
​
    public String getTeacherName() {
        return teacherName;
    }
​
    public void setTeacherName(String teacherName) {
        this.teacherName = teacherName;
    }
​
    public int getTeacherAge() {
        return teacherAge;
    }
​
    public void setTeacherAge(int teacherAge) {
        this.teacherAge = teacherAge;
    }
​
    public Course getCourse() {
        return course;
    }
​
    public void setCourse(Course course) {
        this.course = course;
    }
​
    public List<Student> getStudents() {
        return students;
    }
​
    public void setStudents(List<Student> students) {
        this.students = students;
    }
​
    @Override
    public String toString() {
        return "Teacher{" +
                "teacherName='" + teacherName + '\'' +
                ", teacherAge=" + teacherAge +
                ", course=" + course +
                ", students=" + students +
                '}';
    }
}


​
public class Course {
    private String courseName;
    private int code;
​
    public Course() {
    }
​
    public Course(String courseName, int code) {
        this.courseName = courseName;
        this.code = code;
    }
​
    public String getCourseName() {
        return courseName;
    }
​
    public void setCourseName(String courseName) {
        this.courseName = courseName;
    }
​
    public int getCode() {
        return code;
    }
​
    public void setCode(int code) {
        this.code = code;
    }
​
    @Override
    public String toString() {
        return "Course{" +
                "courseName='" + courseName + '\'' +
                ", code=" + code +
                '}';
    }
}


//第一种方式,使用TypeReference<T>类,由于其构造方法使用protected进行修饰,故创建其子类
    Teacher teacher = JSON.parseObject(COMPLEX_JSON_STR, new TypeReference<Teacher>() {});
// 第二种方式,使用反射
    Teacher teacher1 = JSON.parseObject(COMPLEX_JSON_STR, Teacher.class);

JavaBean_obj —》复杂json格式字符串

Teacher teacher = JSON.parseObject(COMPLEX_JSON_STR, Teacher.class);
    String s = JSON.toJSONString(teacher);

备注:设置实体中的某个属性转json

 

使用JackJson解析数据

 

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
/**
 * JSON工具类
 */
public class JsonUtil {

    /**
     * 将Java对象转化为JSON字符串
     */
    public static String getJSON(Object obj) {
        if (null == obj) {
            return "";
        }
        try {
            ObjectMapper mapper = new ObjectMapper();
            //转换date类型的时候,时间戳
            mapper.getSerializationConfig().with(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
            String jsonStr = mapper.writeValueAsString(obj);
            return jsonStr;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 将JSON字符串转化为Java对象,集合
     */
    public static <T> T getObj(String json, TypeReference<T> ref)
            throws IOException {
        if (null == json || json.length() == 0) {
            return null;
        }
        ObjectMapper mapper = new ObjectMapper();
        mapper.getDeserializationConfig().with(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        return (T) mapper.readValue(json, ref);
    }

    /**
     * 将JSON字符串转化为Java对象,一个对象
     */
    public static Object getObj(String json, Class pojoClass) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            return mapper.readValue(json, pojoClass);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }


}

前端json字符串和对象转换

1.json字符串=》格式对象 使用json.parse(jsonStr)

2.json格式对象=》json格式字符串,使用JSON.stringify(jsonObj);

var jsonObj = {"name":"张三","age":14};

使用JSON.stringify(jsonObj);

 

三哥交流公众号:java一号

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章