亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

無法將 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();

您可以改為使用我的代碼片段,它對我來說工作正?!,F在您可以將 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 關注
  • 175 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號