美文网首页
解决FastJson com.alibaba.fastjson.

解决FastJson com.alibaba.fastjson.

作者: sherlock_6981 | 来源:发表于2018-01-19 14:26 被阅读0次

http://blog.csdn.net/jeffleo/article/details/73612224

FastJson的pom依赖:

com.alibabafastjson1.2.33

1

2

3

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字符串如下所示: 

可以看见,这个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

解决方法: 

用下面这种方式来解析List

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

相关文章

网友评论

      本文标题:解决FastJson com.alibaba.fastjson.

      本文链接:https://www.haomeiwen.com/subject/zmbooxtx.html