【发布时间】:2019-11-25 20:34:49
【问题描述】:
我将从 localhost 数据库获取 JSON。然后,我想把 json 放到 ArrayList 中。我想调用 parseJSON 函数。但 JSON 为空。我应该在哪里调用该函数,非常感谢:))
@Override
protected String doInBackground(Void... voids) {
try {
URL url = new URL(urlWebService);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
StringBuilder sb = new StringBuilder();
InputStream input = con.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(input));
String json;
while ((json = bufferedReader.readLine()) != null) {
sb.append(json + "\n");
}
parseJSON(json);
return sb.toString().trim();
} catch (Exception e) {
return null;
}
}
}
GetJSON getJSON = new GetJSON(
);
getJSON.execute();
}
private void parseJSON(String json) {
Gson gson = new Gson();
Type type = new TypeToken<List<EssayElement>>(){}.getType();
List<EssayElement> mList = gson.fromJson(json, type);
for (EssayElement essayElement : mList){
Log.i("Message: " +
"", essayElement.id + "-" + essayElement.title + "-" + essayElement.essay + "-" + essayElement.date + "-" + essayElement.time);
}
}
使用字符串“json”的空对象引用
【问题讨论】:
-
尝试用
parseJSON(sb.toString());替换parseJSON(json); -
缺少
json=sb.toString()。json变量仍然没有引用。 -
在 parseJSON 函数中,您发送的是空值,因为您没有为“json”设置值,请尝试“发送 sb.toString()”并更改参数
标签: java android json android-asynctask