无法将 json 值传递给函数

我将从本地主机数据库获取 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);

    }

}

带有 String"json" 的空对象引用


摇曳的蔷薇
浏览 90回答 3
3回答

茅侃侃

我建议使用适当的 http 库来处理像 Volley 或 Retrofit 这样的请求...JSON 和错误处理也是内置的,因此可以为此目的完全删除 AsyncTask但是你所拥有的很好,只是json在 while 循环之后不应该使用,它只是 http 响应的最后一行,而不是完整的 json(假设有多行)您真的应该考虑解析 中的结果onPostExecute,甚至可能让 parse 方法返回一个实际对象,或显示到 UI

aluckdog

&nbsp; &nbsp; &nbsp; &nbsp;BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));&nbsp; &nbsp; &nbsp; &nbsp; StringBuilder sb = new StringBuilder();&nbsp; &nbsp; &nbsp; &nbsp; String line = null;&nbsp; &nbsp; &nbsp; &nbsp; while ((line = reader.readLine()) != null) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; sb.append(line + "\n");&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; String json = sb.toString();您可以改为使用我的代码片段,它对我来说工作正常。现在您可以将 son 变量用于您的 private void parseJSON(String json) 函数。

富国沪深

您正在将字符串附加到StringBuilder sb = new StringBuilder();.&nbsp;你必须像这样调用,parseJSON(sb.toString());因为String json只是一个指针不包含你想要的实际字符串。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java