为了账号安全,请及时绑定邮箱和手机立即绑定

无法将 json 值传递给函数

无法将 json 值传递给函数

摇曳的蔷薇 2023-03-31 09:30:25
我将从本地主机数据库获取 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" 的空对象引用
查看完整描述

3 回答

?
茅侃侃

TA贡献1842条经验 获得超21个赞

我建议使用适当的 http 库来处理像 Volley 或 Retrofit 这样的请求...JSON 和错误处理也是内置的,因此可以为此目的完全删除 AsyncTask

但是你所拥有的很好,只是json在 while 循环之后不应该使用,它只是 http 响应的最后一行,而不是完整的 json(假设有多行)

您真的应该考虑解析 中的结果onPostExecute,甚至可能让 parse 方法返回一个实际对象,或显示到 UI


查看完整回答
反对 回复 2023-03-31
?
aluckdog

TA贡献1847条经验 获得超7个赞

       BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

        StringBuilder sb = new StringBuilder();

        String line = null;

        while ((line = reader.readLine()) != null) {

            sb.append(line + "\n");

        }

        String json = sb.toString();

您可以改为使用我的代码片段,它对我来说工作正常。现在您可以将 son 变量用于您的 private void parseJSON(String json) 函数。


查看完整回答
反对 回复 2023-03-31
?
富国沪深

TA贡献1790条经验 获得超9个赞

您正在将字符串附加到StringBuilder sb = new StringBuilder();. 你必须像这样调用,parseJSON(sb.toString());因为String json只是一个指针不包含你想要的实际字符串。



查看完整回答
反对 回复 2023-03-31
  • 3 回答
  • 0 关注
  • 87 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信