如何在java中读取json文件?

如何在java中读取json文件?,java,json,Java,Json,我试图从一个文件中读入这个json数据 [{"name":"Luke","score":50},{"name":"Ryan","score":70}] 代码: 这给了我一个错误: com.google.gson.JsonArray cannot be cast to org.json.JSONObject com.google.gson.JsonArray无法强制转换为org.json.JSONObject 有两个问题: 您的JSON显然是一个数组(包装它的[和]将其送出),您试图将其视为JS

我试图从一个文件中读入这个json数据

[{"name":"Luke","score":50},{"name":"Ryan","score":70}]
代码:

这给了我一个错误:

com.google.gson.JsonArray cannot be cast to org.json.JSONObject com.google.gson.JsonArray无法强制转换为org.json.JSONObject
有两个问题:

  • 您的JSON显然是一个数组(包装它的
    [
    ]
    将其送出),您试图将其视为JSON对象
  • 您混合了两个不同的JSON库—Gson和org.JSON库
  • 坚持使用一个库(在这种情况下为Gson):


    有两个问题:

  • 您的JSON显然是一个数组(包装它的
    [
    ]
    将其送出),您试图将其视为JSON对象
  • 您混合了两个不同的JSON库—Gson和org.JSON库
  • 坚持使用一个库(在这种情况下为Gson):


    感谢您的回复,非常有用,唯一的问题是我在循环中的jsonArray下得到一个错误,表示只能迭代一个数组或java.lang.IterableThanks的回复,非常有用,唯一的问题是我在循环中的jsonArray下得到一个错误,表示只能迭代一个数组或java.lang.Iterable的实例 com.google.gson.JsonArray cannot be cast to org.json.JSONObject
    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);
    }