我试图从文件中读取这个json数据
[{"name":"Luke","score":50},{"name":"Ryan","score":70}]
代码:
JsonParser parser = new JsonParser();
try{
Object obj = parser.parse(new FileReader("C:/Users/user/Documents/HighscoresJSON.json"));
JSONObject jsonObject = (JSONObject) obj;
String usersName = (String) jsonObject.get("name");
System.out.println("Name of user: " + usersName);
int usersScore = (int) jsonObject.get("score");
System.out.println("Score: " + usersScore);
这给了我错误:
com.google.gson.JsonArray cannot be cast to org.json.JSONObject
答案 0 :(得分:5)
有几个问题:
[
和]
包装它将它放弃)并且您正在尝试将其视为JSON对象。坚持使用一个库(本例中为Gson):
Object obj = parser.parse(new FileReader("something.json"));
JsonArray jsonArray = (JsonArray) obj;
for (JsonElement element : jsonArray) {
JsonObject jsonObject = element.getAsJsonObject();
String usersName = jsonObject.get("name").getAsString();
System.out.println("Name of user: " + usersName);
int usersScore = jsonObject.get("score").getAsInt();
System.out.println("Score: " + usersScore);
}