数据解析(三):FastJson

前端之家收集整理的这篇文章主要介绍了数据解析(三):FastJson前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

一.fastJson与Gson的用法基本一致

二.直接贴上代码

//把java对象转换成json字符串
    public void JavaToJson() {
        Student stu = new Student("李毅",23);
        String s = JSON.toJSONString(stu);
        System.out.println("javaToJSon:" + s);
        //I/System.out: javaToJSon:{"name":"李毅","age":23}
    }

    //把list集合转换成json字符串
    public void ListToJson() {
        ArrayList<Student> data = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            Student stu = new Student("N" + i,i);
            data.add(stu);
        }
        String s = JSON.toJSONString(data);
        System.out.println("listToJSON:" + s);
        //System.out: listToJSON:[{"name":"N0","age":0},{"name":"N1","age":1},{"name":"N2","age":2}]
    }

    //把json字符串转换成java对象
    public void jsonToJava() {
        Student student = new Student("李毅",23);
        String s = JSON.toJSONString(student);
        JSON.parSEObject(s,Student.class);

        System.out.println("jsonToJava:" + student.toString());
        //I/System.out: listToJSON:[{"name":"N0","age":2}]
    }

    //把json字符串转换成list集合对象
    public void JsonToList() {
        ArrayList<Student> data = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            Student stu = new Student("N" + i,i);
            data.add(stu);
        }
        String json = JSON.toJSONString(data);
      ArrayList<Student> coll = JSON.parSEObject(json,new TypeReference<ArrayList<Student>>(){}.getType());
        System.out.println("jsonToList:" + coll.size());
        // I/System.out: jsonToList:3

    }

猜你在找的Json相关文章