Java中奇怪的ClassCastException

时间:2017-09-26 10:04:34

标签: java generics

我知道这是基本的,很多人都觉得这是一个愚蠢的问题。但是,我对它的行为很感兴趣。

我有一个方法,它采用List<String>

private WHT21940000Data populateObjectFromJsonList(List<String> subList) {
    String s = subList.get(0); // problem line
    // more code to follow...
}

现在,如上面代码段中的问题行所示,我从1中提取了一个值(List)。

现在,我的代码编译但在运行时它抛出以下异常:

Uncaught exception: java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String

当我使用generic形式的List<String>时,我应该只能从我的List<String>中检索字符串。那为什么我会得到这个例外?

P.S。:下面是调用代码: -

     List<List<String>> jsonConvertedList = mapper.readValue(json, List.class);
        for (List<String> subList : jsonConvertedList) {
        WHT21940000Data pojo = populateObjectFromJsonList(subList);
        data.add(pojo);
     }

以下是json字符串输入,它是所有数据类型的混合

[
    [1,21940000,1905386136,null,"KR","akshay","04/06/2017","03/06/2017",2017,9,40,"JPY",7478,"JPY",7478,"WHT (Residen",null,0,"03/06/2017","03/06/2017","20170604",null],
    [2,21940000,1903732187,null,"KR",null,"06/06/2017","05/06/2017",2017,9,40,"JPY",608547485,"JPY",608547485,"WHT (Non-Resi",null,0,"05/06/2017","05/06/2017","20170606",null],
    [3,21940000,2001898163, ............... ]
.
.
.
.
.
.
.
.
]

1 个答案:

答案 0 :(得分:1)

感谢Jon Skeet对上述评论的指导。

您的主要评论是在这里引用:

  

“不要假设包含非字符串值的JSON只包含   字符串“

我必须使用Object代替String然后问题就消失了:

List<List<Object>> jsonConvertedList = mapper.readValue(json, List.class);