Java ClassCastException: org.json.simple.JSONArray 不能转换为 org.json.simple.JSONObject

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35094781/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 16:18:01  来源:igfitidea点击:

ClassCastException: org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject

javajson

提问by kroe761

I am trying to parse a son file, and I don't know what I'm doing wrong (of course, I don't really know what I'm doing right, either).

我正在尝试解析一个子文件,但我不知道自己做错了什么(当然,我也不知道自己在做什么对)。

file.json

文件.json

[{  
"arrOne":{  
    "one":"a",
    "two":"b",
    "three":"c",
    "four":"d",
    "five":"e"
},
"elemTwo":"f",
"elemThree":"g",
"elemFour":"h",
"elemFive":"i",
"arrSix":[{  
    "six":1,
    "seven":2,
    "eight":"j"
}]}]

code:

代码:

import java.io.FileNotFoundException;
import java.io.FileReader;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
//...........
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("/path/to/file.json"));
JSONObject json = (JSONObject) obj;
String unit = (String) json.get("elemTwo");
System.out.println(unit);

I get the error ClassCastException: org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject. Truthfully, I have no idea what I'm doing. Any help would be great! Thanks!

我收到错误 ClassCastException: org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject。说实话,我不知道我在做什么。任何帮助都会很棒!谢谢!

回答by adushenin

You should cast your objtoJsonArrayinstead of JsonObject, because your json file has []at the root.

您应该使用objtoJsonArray而不是JsonObject,因为您的 json 文件[]位于根目录。

回答by Abdelhak

When the JSonParserparses the file, it's returning it as a JSONArray, to solve it try to use this:

JSonParser解析文件时,它将它作为 a 返回JSONArray,要解决它尝试使用这个:

    JSONObject obj = (JSONObject)obj;
    JSONObject elem = (JSONObject)obj.get("0");
    String unit = (String) elem.get("elemTwo");
    System.out.println(unit);

回答by sushant gosavi

you are getting JSONArray not JsonObject

你得到的是 JSONArray 而不是 JsonObject

JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("/path/to/file.json"));
JSONArray json = (JSONArray) obj;

Than loop this and get jsonobject

比循环这个并获得 jsonobject