com.alibaba的fastjson简介

  从前台接收json封装的list数据,在后台接收时一直报错,com.alibaba.fastjson.JSONObject
cannot be cast to xxx,

在读取json文件,返回页面json串时,发生如下错误

工作中遇到的坑

Fastjson简介

Fastjson是一个Java语言编写的高性能功能完善的JSON库。它采用一种“假定有序快速匹配”的算法,把JSON Parse的性能提升到极致,是目前Java语言中最快的JSON库。Fastjson接口简单易用,已经被广泛使用在缓存序列化、协议交互、Web输出、Android客户端等多种应用场景

  使用这种方式接收可以接收

java.lang.ClassCastException: com.alibaba.fastjson.JSONArray cannot be cast to com.alibaba.fastjson.JSONObject

FastJson的pom依赖:

最近老遇到一个异常 [com.alibaba.fastjson.JSONObject cannot be cast to
xxx]
,而且是偶发,就单独把数据用fastjson和gson去反复解析,发现并没有任何错误,经过分析,突然发现每次单独去执行出现异常的模块时,并不会出现该异常,当执行了某个操作时,再回来执行出现问题的逻辑,就会出现。

Maven引入

<dependency>

    <groupId>com.alibaba</groupId>

    <artifactId>fastjson</artifactId>

    <version>1.2.37</version>

</dependency>

 

 1 @RequestMapping(value = "/insertUser", method = RequestMethod.POST) 2 public ResultT insertUser(@RequestBody Map<String,List<User>> map){ 3     List<User> userList = map.get("insertUserList");   4 } 5  6 //前台json格式 7 { 8     "insertUserList": [ 9         {10             "firstName": "Brett",11             "lastName": "McLaughlin",12             "email": "aaaa"13         },14         {15             "firstName": "Jason",16             "lastName": "Hunter",17             "email": "bbbb"18         },19         {20             "firstName": "Elliotte",21             "lastName": "Harold",22             "email": "cccc"23         }24     ]25 }

1.工具类

读取JSON文件转换成string的方法

    public static String ReadFile(String Path) {

        BufferedReader reader = null;

        String laststr = "";
        try {
            FileInputStream fileInputStream = new FileInputStream(Path);
            InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "utf-8");
            reader = new BufferedReader(inputStreamReader);
            String tempString = null;
            while ((tempString = reader.readLine()) != null) {
                laststr += tempString;
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return laststr;
    }

com.alibabafastjson1.2.33

找到问题规律就好办了,去 github fastjson issues 和
google去找类似问题,发现也存在该问题,在issues上没找到解决方法,后来在google搜索到了一个解决办法。

常用api

  1. 将对象序列化成json字符串

String com.alibaba.fastjson.JSON.toJSONString(Object object)

  1. 将json字符串反序列化成对象

<T> Project com.alibaba.fastjson.JSON.parseObject(String text,
Class<T> clazz)

  1. 将json字符串反序列化成JSON对象

JSONObject com.alibaba.fastjson.JSON.parseObject(String text)

4.根据key 得到json中的json数组

JSONArray com.alibaba.fastjson.JSONObject.getJSONArray(String key)

  1. 根据下标拿到json数组的json对象

JSONObject com.alibaba.fastjson.JSONArray.getJSONObject(int
index)

6.. 根据key拿到json的字符串值

String com.alibaba.fastjson.JSONObject.getString(String key)

  1. 根据key拿到json的int值

int com.alibaba.fastjson.JSONObject.getIntValue(String key)

  1. 根据key拿到json的boolean值

boolean com.alibaba.fastjson.JSONObject.getBooleanValue(String key)

调用类

    @RequestMapping(value = "menu")
    @ResponseBody
    public JSONObject menu(String id) {
        String url = HttpContext.current().getRequest().getServletContext().getRealPath("/");
        if (id.equals("1")) {
            url = url + "/static/json/images.json";
        } else if (id.equals("2")) {
            url = url + "/static/json/linksList.json";
        } 
        String output = FileUtils.ReadFile(url);
        System.out.println(output);
        JSONObject JSONObject =  JSON.parseObject(output);
        return JSONObject;
    }

1

问题:

当先解析一个无data的数据返回时:

BaseResult baseResult = JSON.parseObject(data
                        , new TypeReference<BaseResult>() {})

然后在后面的逻辑上解析一个存在data的数据返回时:

BaseResult<LoginRes> baseResult = JSON.parseObject(data
                        , new TypeReference<BaseResult<LoginRes>>() {})

这个时候就会出现[com.alibaba.fastjson.JSONObject cannot be cast to
xxx.LoginRes] 异常。

实例说明

Project类

package com.json;

import java.util.List;

public class Project {
    String pjName;
    boolean waibao;
    public boolean isWaibao() {
        return waibao;
    }
    public void setWaibao(boolean waibao) {
        this.waibao = waibao;
    }
    List<Factory> l_factory;
    //List<Worker> worker;
    public String getPjName() {
        return pjName;
    }
    public void setPjName(String pjName) {
        this.pjName = pjName;
    }
    public List<Factory> getL_factory() {
        return l_factory;
    }
    public void setL_factory(List<Factory> l_factory) {
        this.l_factory = l_factory;
    }


}

Factory类

package com.json;

import java.util.List;

public class Factory {

    String fcName;
    List<Worker> l_worker;
    public String getFcName() {
        return fcName;
    }
    public void setFcName(String fcName) {
        this.fcName = fcName;
    }
    public List<Worker> getL_worker() {
        return l_worker;
    }
    public void setL_worker(List<Worker> l_worker) {
        this.l_worker = l_worker;
    }

}

Worker类

package com.json;

public class Worker {

    String name;
    String sex;
    int age;
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }

}

测试类

package com.json;

import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public class TestFastJson {

    public static void main(String args[]) {
        TestFastJson tfj = new TestFastJson();
        Project prj = tfj.init();
        String json= tfj.getJsonString(prj);
        System.out.println("json="+json);
        //json={"l_factory":[{"fcName":"东软","l_worker":[{"age":30,"name":"乔佳飞","sex":"男"},{"age":25,"name":"李帅飞","sex":"女"}]},{"fcName":"亚信","l_worker":[{"age":26,"name":"王新峰","sex":"男"},{"age":0}]}],"pjName":"接口自动化","waibao":true}
        System.out.println("waibao="+tfj.getJsonValueObj(json, "waibao", Boolean.class));
        //waibao=true
        JSONArray array = (JSONArray) tfj.getJsonValueObj(json, "l_factory", JSONArray.class);
        System.out.println("array="+array.toString());
        //array=[{"fcName":"东软","l_worker":[{"sex":"男","name":"乔佳飞","age":30},{"sex":"女","name":"李帅飞","age":25}]},{"fcName":"亚信","l_worker":[{"sex":"男","name":"王新峰","age":26},{"age":0}]}]
        String jsonArr = tfj.getJsonArrayValue(array, 0, "fcName");
        System.out.println("fcName="+jsonArr);
        //fcName=东软
        JSONArray array2 = tfj.getJsonArrayValueIsArray(array, 0, "l_worker");
        System.out.println("array2="+array2.toString());
        //array2=[{"sex":"男","name":"乔佳飞","age":30},{"sex":"女","name":"李帅飞","age":25}]
        String json2 = tfj.getJsonArrayValue(array2, 0);
        System.out.println("json2="+json2);
        //json2={"sex":"男","name":"乔佳飞","age":30}

        /*以下输出
        name=乔佳飞
        sex=男
        age=30
        jsonArr2=男

         * */
        System.out.println("name="+tfj.getJsonValueObj(json2, "name", String.class));
        System.out.println("sex="+tfj.getJsonValueObj(json2, "sex", String.class));
        System.out.println("age="+tfj.getJsonValueObj(json2, "age", Integer.class));

        String jsonArr2 = tfj.getJsonArrayValue(array2, 0, "sex");
        System.out.println("jsonArr2="+jsonArr2);

        /*以下输出
         接口自动化
        东软
        乔佳飞
         */
        System.out.println(tfj.getJsonValue(json));
        System.out.println(tfj.getJsonValue(json,"l_factory"));
        System.out.println(tfj.getJsonValue(json,"l_factory","l_worker"));

    }
    public static void main1(String args[]) {
        TestFastJson tfj = new TestFastJson();
        Project prj = tfj.init();
        String json= tfj.getJsonString(prj);
        prj.setPjName("序列化后修改pjname");
        System.out.println(prj.getPjName());//序列化后修改pjname
        Project po = JSON.parseObject(json,Project.class);
        System.out.println(po.getPjName());//接口自动化
    }

    public void tt(Class clazz) {
        System.out.println(clazz.getSimpleName());
        if(clazz.getName().equals("String")) {
            System.out.println("stringllala");
        }
    }
    public Project init() {
        Project pj = new Project();
        Factory ft1 = new Factory();
        Factory ft2 = new Factory();
        Worker wk1 = new Worker();
        wk1.setName("乔佳飞");
        wk1.setSex("男");
        wk1.setAge(30);

        Worker wk2 = new Worker();
        wk2.setName("李帅飞");
        wk2.setSex("女");
        wk2.setAge(25);

        Worker wk3 = new Worker();
        wk3.setName("魏晓博");
        wk3.setSex("男");
        wk3.setAge(27);

        Worker wk4 = new Worker();
        wk3.setName("王新峰");
        wk3.setSex("男");
        wk3.setAge(26);

        List<Worker> workers1 = new ArrayList<Worker>();
        workers1.add(wk1);
        workers1.add(wk2);

        List<Worker> workers2 = new ArrayList<Worker>();
        workers2.add(wk3);
        workers2.add(wk4);

        ft1.setFcName("东软");
        ft1.setL_worker(workers1);

        ft2.setFcName("亚信");
        ft2.setL_worker(workers2);

        List<Factory> factorys = new ArrayList<Factory>();
        factorys.add(ft1);
        factorys.add(ft2);

        pj.setPjName("接口自动化");
        pj.setWaibao(true);
        pj.setL_factory(factorys);

        return pj;
    }

    /**
     * 
     * 将对象转换成json
     * */
    public String getJsonString(Object obj) {        
        String json= JSON.toJSONString(obj);
        return json;
    }

    /**
     * 根据key得到json的value
     * */
    public String getJsonValue(String json) {
        JSONObject jo = JSON.parseObject(json);
        String value = jo.getString("pjName");
        return value;
    }

    /**
     * 根据key得到json的集合
     * */
    public JSONArray getJsonArray(String json, String key) {
        JSONObject jo = JSON.parseObject(json);

        JSONArray array = jo.getJSONArray(key);

        return array;
    }

    /**
     * 根据下标得到json数组的值
     * */
    public String getJsonArrayValue(JSONArray array, int index) {
        JSONObject jo_fc = array.getJSONObject(index);
        String json = jo_fc.toJSONString();
        return json;
    }

    /**
     * 根据下标得到json数组的值,再根据key得到该值的value,该值类型是String
     * */
    public String getJsonArrayValue(JSONArray array, int index, String key) {
        JSONObject jo_fc = array.getJSONObject(index);
        String value = jo_fc.getString(key);
        return value;
    }
    /**
     * 根据下标得到json数组的值,再根据key得到该值的value,该值类型是JSONArray
     * */
    public JSONArray getJsonArrayValueIsArray(JSONArray array, int index, String key) {
        JSONObject jo_fc = array.getJSONObject(index);
        JSONArray arrayNew = jo_fc.getJSONArray(key);        
        return arrayNew;
    }
    /**
     * 根据对象的类型,自动识别获取该对象的值
     * */
    public Object getJsonValueObj(String json, String key, Class clazz) {
        JSONObject jo = JSON.parseObject(json);
        if(clazz.getSimpleName().equals("String")) {
            String value = jo.getString(key);
            return value;
        }else if(clazz.getSimpleName().equals("Integer")) {
            Integer value = jo.getInteger(key);
            return value;
        }else if (clazz.getSimpleName().equals("Boolean")) {
            Boolean value = jo.getBoolean(key);
            return value;
        }else if(clazz.getSimpleName().equals("JSONArray")) {
            JSONArray array = jo.getJSONArray(key);
            return array;
        }
        else {
            return "error, 暂不支持的类型:"+clazz.toString();
        }        

    }

    public String getJsonValue(String json, String key) {
        JSONObject jo = JSON.parseObject(json);

        JSONArray array = jo.getJSONArray(key);
        JSONObject jo_fc = array.getJSONObject(0);
        String value = jo_fc.getString("fcName");
        return value;
    }

    public String getJsonValue(String json, String key, String keyW) {
        JSONObject jo = JSON.parseObject(json);

        JSONArray array = jo.getJSONArray(key);
        JSONObject jo_fc = array.getJSONObject(0);
        JSONArray arrayW = jo_fc.getJSONArray(keyW);
        JSONObject jo_wk = arrayW.getJSONObject(0);
        String value = jo_wk.getString("name");
        int age = jo_wk.getIntValue("age");
        //System.out.println(age);
        return value;
    }
}

 

2.错误点

2

解决方案:

把无data的数据返回解析代码改为:

BaseResult<Void> baseResult = JSON.parseObject(data
                        , new TypeReference<BaseResult<Void>>() {})

查了下资料,该问题是由于解析器缓存引起。

Github/fastjson

工具类返回的是属于string类型,而不是JSONARRAY

3

3.解决方法

    String output = FileUtils.ReadFile(url);
    System.out.println(output);
    JSONArray jsonArray =  JSONObject.parseArray(output);
    return jsonArray;

使用JSONObject.parseArray(output)方法,将string转化为JSONAarray。

4

5

听闻FastJson使用特别的算法,速度非常快,甚至快过Google的protobuf,所以选择使用FastJson来做Json的处理,具体产生Json字符串的代码如下:

ListstudentList=newArrayList();Student
student1=newStudent();student1.setId(1);ListresultNumbers=newArrayList();resultNumbers.add(“12”);resultNumbers.add(“23”);student1.setResultNumber(resultNumbers);Student
student2=newStudent();student2.setId(1);ListresultNumbers2=newArrayList();resultNumbers2.add(“45”);resultNumbers2.add(“56”);student2.setResultNumber(resultNumbers);studentList.add(student1);studentList.add(student2);Mapmap=newHashMap();map.put(“count”,2);map.put(“studentList”,
studentList);Stringjson=JSON.toJSONString(map,true);

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

此时的Json字符串如下所示: 

图片 1

可以看见,这个json字符串内有一个内置的List

出现题目的cast Exception的解析方式如下:

HashMap parseMap = JSON.parseObject(json, HashMap.class);List
studentList1 = (List) parseMap.get(“studentList”);for(Student student :
studentList1){ // Exception    System.out.println(student.getId() +”
“);}

1

2

3

4

5

debug发现,其实那是一个JsonObject

图片 2

解决方法: 

用下面这种方式来解析List

List studentList1 =
JSON.parseArray(JSON.parseObject(json).getString(“studentList”),
Student.class);

相关文章