gpt4 book ai didi

java - 组织.json.JSONException : End of input at character 0 of while creating a JSON Object

转载 作者:行者123 更新时间:2023-11-30 02:23:15 30 4
gpt4 key购买 nike

我只是想像这样创建 JSON 对象:

JSONObject jsonObject = new JSONObject(new JsonUtility().execute(UrlUtility.url + "/" + lessonUrl).get());

此处发生错误 ^ 在 catch block 中收到消息:

org.json.JSONException: End of input at character 0 of 

JsonUtility 类如下(我相信问题不在那里但仍然存在):

    private class JsonUtility extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
String result = "";
try {
InputStream inputStream = new URL(params[0]).openStream();
BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"), 8);
StringBuilder sBuilder = new StringBuilder();

// Reading Json into StringBuilder
String line = null;
while ((line = bReader.readLine()) != null) {
sBuilder.append(line + "\n");
}

inputStream.close();
// Converting Json from StringBuilder to String
result = sBuilder.toString();

} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}

您会看到响应是由字符串连接而成的(由于应用程序逻辑)。最后的字符串是:http://itvdn-api.azurewebsites.net/api/courses/test-driven-development/tdd-introduction。如您所见,当我重定向到该链接时,它会给出 JSON 响应。

我已尝试评估此 UrlUtility.url 并收到: enter image description here

char 数组的奇怪结尾让我感到困惑。也许是问题所在。尝试使用 String.replaceAll("'\u0000'0", "") 替换这些字符。没有工作。

请帮忙。将不胜感激任何想法。谢谢。


编辑:

此外,当我将链接硬编码为:

JSONObject jsonObject = new JSONObject(new JsonUtility().execute("http://itvdn-api.azurewebsites.net/api/courses/test-driven-development/tdd-introduction").get());

有效!


编辑 #2 @ ρяσѕρєя K

result = sBuilder.toString(); 是空的 - "" 因为它无法解析连接的字符串。

注意:在此应用程序中,我一直使用具有不同链接的相同解析器,例如http://itvdn-api.azurewebsites.net/api/courses这工作正常(但没有与链接连接)

最佳答案

/**
* Convert InputStream into String
* @param is
* @return
* @throws IOException Throws an IO Exception if input stream cannot be read
*/
public static String stringFromInputStream(InputStream is) throws IOException {
if (is != null) {
byte[] bytes = new byte[1024];
StringBuilder x = new StringBuilder();
int numRead = 0;
while ((numRead = is.read(bytes)) >= 0)
x.append(new String(bytes, 0, numRead));
return x.toString();
}
else {
return "";
}
}

使用此方法读取输入流并获取字符串。

关于java - 组织.json.JSONException : End of input at character 0 of while creating a JSON Object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28167573/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com