首页 > 解决方案 > 为什么json解析器程序找不到数组?

问题描述

请帮助我理解为什么这个 java 程序没有从 json 文件中找到数组。我没有通过谷歌找到类似类型的 json 文件,所以请教育我。

错误:

C:\temp\example.json
org.json.JSONException: JSONObject["result"] not found.
    at org.json.JSONObject.get(JSONObject.java:572)
    at org.json.JSONObject.getJSONArray(JSONObject.java:765)
    at JsonParsingMachine.main(JsonParsingMachine.java:17)

.java 内容:

import java.io.FileReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import org.json.*;

public class JsonParsingMachine {

    public static void main(String[] args) {
        String tiedosto = "C:/temp/example.json";

        System.out.println(Paths.get(tiedosto));
        try {
            String contents = new String((Files.readAllBytes(Paths.get(tiedosto))));
            JSONObject o = new JSONObject(contents);
            JSONArray res = o.getJSONArray("result");

            for (int i = 0; i < res.length(); i++) {
                System.out.println();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

json 文件(example.json)

{
  "quoteResponse" : {
    "result" : [ {
      "language" : "en-US",
      "region" : "US",
      "quoteType" : "EQUITY",
      "quoteSourceName" : "Nasdaq Real Time Price",
      "triggerable" : true
    } ]
  }
}

标签: javajsonorg.json

解决方案


result数组在quoteResponseJSONObject 中。你需要这样做:

JSONObject o = new JSONObject(contents);
JSONObject quoteResponse = o.getJSONObject("quoteResponse");
JSONArray res = quoteResponse.getJSONArray("result");

推荐阅读