fastjson 从json文件读取数据出现 illegal state : 1002

zpqajqem  于 2021-11-27  发布在  Java
关注(0)|答案(2)|浏览(1534)
File file = new File("C:/Users/18191/Desktop/ymj3.json");
        FileInputStream fileInputStream = new FileInputStream(file.getAbsoluteFile());
        JSONReader reader = new JSONReader(new InputStreamReader(fileInputStream,"UTF-8"));
        reader.startObject();
        while(reader.hasNext()) {
            String key = reader.readString()    ;
            System.out.println(key);
            //VO vo = reader.readObject(VO.class);
            // handle vo ...

        }

        reader.endObject();
        reader.close();

while循环第一次没有问题,但是循环第二次时,reader.hasNext()就会报错com.alibaba.fastjson.JSONException: illegal state : 1002

数据如下

{"key":"value","anotherKey":[
{"begin_int":"1677721","end_int":"1677747"},
{"begin_int":"1687552","end_int":"1690828"},
{"begin_int":"1690905","end_int":"1690931"},
{"begin_int":"1690931","end_int":"1690956"},
{"begin_int":"1690956","end_int":"1690982"}
],"thirdKey":{"subKey":"subVal","anotherSubKey":["1","2","3"]}}
nwlls2ji

nwlls2ji1#

你对readString方法理解不对。 调用readString方法会移动游标的,在你的例子中你调用了一次,然后游标到了冒号那里, 然后hasnext进行判断,因为遇到了 : 所以就报错了。 正确的写法如下

while(reader.hasNext()) {
String key = reader.readString();
String value = reader.readString();
System.out.println(key);
System.out.println(value);
}

iq0todco

iq0todco2#

谢谢!,花了很长时间才发觉是这个问题,你的回答和我猜测的一样。

相关问题