zoukankan      html  css  js  c++  java
  • FastJson介绍

    fastjson主要是为了实现json对象和javaBean对象转换,javaBean和json字符串转换,json对象和json字符串相互转换。

    fastjson包里面主要有3个类,Json、JsonArray、JsonObject,三者关系是:

    image

    其中jsonObject代表json对象,JsonArray代表json对象数据,Json代表JsonObject和JsonArray的转化

    2、三个类的用途和方法

    jsonObject:解析json数组,获取对象中的只,通常使用类里面的get方法

    jsonArray:Json对象数组,通常通过迭代器取得其中的jsonJsonObject,再利用jsonObject的get方法进行取值

    json:主要是jsonObject、jsonArray、javaBean实现类型相互转换,转换后取值还是按照各自的方法进行

    3、相互转换

    (1)字符串转换成jsonObject

     JSONObject jsonObject = JSON.parseObject(JSON_OBJ_STR);
     (2)jsonObject转换成字符串
     String s = JSON.toJSONString(jsonObject)
     (3)字符串转化成jsonArray
    将JSON字符串数组转化为JSONArray,通过JSON的parseArray()方法。JSONArray本质上还是一个数组,对其进行遍历取得其中的JSONObject,然后再利用JSONObject的get()方法取得其中的值。
    (4)jsonArray转换成字符串
     String s = JSON.toJSONString(jsonArray);
    (5)字符串转化成javaBean
            // 第一种方式
            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);
    ​(6)javaBean转化成字符串
       String s = JSON.toJSONString(lily);
    (7)jsonArray转化成javaBean-list
            // 方式一:
            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);
    ​(8)javaBean-list转化成json字符串数组
     String s = JSON.toJSONString(students);
  • 相关阅读:
    在安卓上用Termux安装sqlmap
    地址转换函数
    字节操作函数
    主机字节序和网络字节序
    20191231 Spring官方文档(Core 1.13-1.14)
    20191230 Spring官方文档(Core 1.12)
    20191230 Tomcat权威指南-读书摘要系列【归档】
    20191230 On Java8【归档】
    20191227 Java8 日期时间API
    20191226 Spring官方文档(Core 1.11)
  • 原文地址:https://www.cnblogs.com/saifei1125/p/12162815.html
Copyright © 2011-2022 走看看