Java org.json.JSONException:在创建json对象时,在的字符0处结束输入
我只是尝试创建JSON对象,如下所示:Java org.json.JSONException:在创建json对象时,在的字符0处结束输入,java,android,json,Java,Android,Json,我只是尝试创建JSON对象,如下所示: JSONObject jsonObject = new JSONObject(new JsonUtility().execute(UrlUtility.url + "/" + lessonUrl).get()); 此处发生错误,^在catch块中收到消息: org.json.JSONException: End of input at character 0 of JsonUtility类如下(我相信问题不在这里,但仍然存在): 它起作用了 编辑#
JSONObject jsonObject = new JSONObject(new JsonUtility().execute(UrlUtility.url + "/" + lessonUrl).get());
此处发生错误,^在catch
块中收到消息:
org.json.JSONException: End of input at character 0 of
JsonUtility
类如下(我相信问题不在这里,但仍然存在):
它起作用了
编辑#2@ρ#σρѕρєK
result=sBuilder.toString()
为空-“”
,因为它无法解析连接的字符串
注意:我在这个应用程序中使用了相同的解析器和不同的链接,例如,这很好(但是没有链接连接)
使用此方法读取inputstream并获取字符串。最终响应是什么
result=sBuilder.toString()代码>?并且对于lineUsebyte[]bytes=new byte[1024]的json字符串也不需要添加“\n”;StringBuilder x=新的StringBuilder();int numRead=0;而((numRead=is.read(bytes))>=0)x.append(新字符串(bytes,0,numRead))代码>@ρцσѕρєцK检查已编辑post@jitainsharma我应该在InputStream的重写方法read()
中写什么?它默认返回0。我真的不知道如何使用它。我相信我应该在doInBackground
方法中使用此方法,但是所有的bufferedreader
都不工作。如果你能展示一个实际的使用示例,我会发布这个方法来获取inputstream并读取字节,附加到stringBuilder中,这里我们一次读取1024个字节。另外,如果您使用“+”\n”,请删除此项并检查。是的,现在我明白了。谢谢这似乎奏效了
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;
}
}
JSONObject jsonObject = new JSONObject(new JsonUtility().execute("http://itvdn-api.azurewebsites.net/api/courses/test-driven-development/tdd-introduction").get());
/**
* 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 "";
}
}