错误:预期为BEGIN_ARRAY,但位于第1行第1列路径$

时间:2019-01-08 06:43:52

标签: java android json gson

我正在尝试解析如下所示的JSON文件:

[
    {"character": "㐭", "definition": "blabla", "pinyin": ["lin"]},
    // some more 
    {"character": "㐱", "definition": "blabla", "pinyin": ["zhen"]}
]

P.S。我的json文件中没有// some more

哪个位于res / raw / dictionary.json文件夹中。但是我得到了异常Expected BEGIN_ARRAY but was STRING at line 1 column 1 path $。我正在获取这样的数据:

InputStream is = getResources().openRawResource(R.id.dictionary);
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try {
    Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
    int n;
    while((n = reader.read(buffer)) != -1) {
        writer.write(buffer, 0, n);
    }
} catch (UnsupportedEncodingException e) {
    e.printStackTrace();
    finish(); // For now just finishing activity, gonna add handling later
} catch (IOException e) {
    e.printStackTrace();
    finish();
} finally {
    try {
        is.close();
    } catch (IOException e) {
        e.printStackTrace();
        finish();
    }
}
String json = writer.toString();
JSONArray dictionary = new JSONArray(json);
// Do stuff with Array

首先,我认为错误是因为我解析json的方式而出现的,但是当我注释掉然后删除所有解析机制时,它仍然向我显示此错误。似乎是在android加载资源时发生的,但我不确定。我尝试将json修改为以下内容:

{
  "characters": [
      {"character": "㐭", "definition": "blabla", "pinyin": ["lin"]},
      // some more
      {"character": "㐱", "definition": "blabla", "pinyin": ["zhen"]}
  ]
}

并更改解析机制

// Get resources
String json = writer.toString();
JSONObject dictionaryObj = new JSONObject(json);
JSONArray dictionary = dictionaryObj.getJSONArray("characters");

但是那也没有帮助。这里有什么问题?

N.B。:问题是我什至无法测试任何解决方案,因为未加载活动,因此在gradle构建期间的“运行任务”部分中会出现错误

4 个答案:

答案 0 :(得分:0)

Json应该是:(我删除了// some more

{
  "characters": [
      {"character": "㐭", "definition": "blabla", "pinyin": ["lin"]},
      {"character": "㐱", "definition": "blabla", "pinyin": ["zhen"]}
  ]
}

答案 1 :(得分:0)

func urlSession(
        _ session: URLSession,
        task: URLSessionTask,
        didReceive challenge: URLAuthenticationChallenge,
        completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void)
{
    var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling
    var credential: URLCredential?

    if let taskDidReceiveChallenge = taskDidReceiveChallenge {
        (disposition, credential) = taskDidReceiveChallenge(session, task, challenge)
    } else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
        let host = challenge.protectionSpace.host

        if
            let serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicy(forHost: host),
            let serverTrust = challenge.protectionSpace.serverTrust
        {
            if serverTrustPolicy.evaluate(serverTrust, forHost: host) {
                disposition = .useCredential
                credential = URLCredential(trust: serverTrust)
            } else {
                disposition = .cancelAuthenticationChallenge
            }
        }
    } else {
        if challenge.previousFailureCount > 0 {
            disposition = .rejectProtectionSpace
        } else {
            credential = self.credential ?? session.configuration.urlCredentialStorage?.defaultCredential(for: challenge.protectionSpace)

            if credential != nil {
                disposition = .useCredential
            }
        }
    }

    completionHandler(disposition, credential)
}

对于Json以上

   {
      "characters": [
          {"character": "㐭", "definition": "blabla", "pinyin": ["lin"]},
          // some more
          {"character": "㐱", "definition": "blabla", "pinyin": ["zhen"]}
      ]
    }

尝试

答案 2 :(得分:0)

您需要将以下数据解析为JSONObject,而不是在Root上以JSONArray的形式接收数据:

[
    {"character": "㐭", "definition": "blabla", "pinyin": ["lin"]},
    // some more 
    {"character": "㐱", "definition": "blabla", "pinyin": ["zhen"]}
]

对于此类数据,解析为:

// Get resources
String json = writer.toString();
JSONArray arr = new JSONArray(json);
// Then parse your objects like below
for (int i=0; i < arr.length(); i++) {
    JSONObject character = arr.getJSONObject(i); // this will provide you all json objects to be parse.
}

答案 3 :(得分:0)

好吧,这个问题不在JSON解析机制中,而是在我通过重新启动项目解决的Android Studio错误中。