簡體   English   中英

無法將字符串轉換為JSONArray或JSONObject

[英]Unable to Convert String to Either JSONArray or JSONObject

我無法將String轉換為JSONArray或JSONObject。 這是下面的代碼:

JSONArray entries = WebRequest.execute(request);
if(entries!=null){          
    try{
        String temp  = entries.getJSONObject(0).getString(WebRequest.CONTENT);    
        String s = temp.toString();
        JSONArray cont = new JSONArray(s);

        Toast.makeText(getBaseContext(), cont.toString(), Toast.LENGTH_LONG).show();
    }catch(Exception e){                
    }
}

這是String結果:

“[{\\ ID_PROJECT \\”:528,\\ “NM_PROJECT \\”:\\ “TestProject \\” ,, \\ “NM_TASK \\”:\\ “TestTask \\”}]”

使用此代碼時,我無法吐司。

這是您的json字符串的json解析

String OutputData = "";
JSONObject jsonResponse;

try {

      /****** Creates a new JSONObject with name/value mappings from the JSON string. ********/
      jsonResponse = new JSONObject("{\"data\":[{\"ID_PROJECT\":528,\"NM_PROJECT\":\"TestProject\",\"NM_TASK\":\"TestTask\"}]}");

      /***** Returns the value mapped by name if it exists and is a JSONArray. ***/
      /*******  Returns null otherwise.  *******/
      JSONArray jsonMainNode = jsonResponse.optJSONArray("data");

      /*********** Process each JSON Node ************/

      int lengthJsonArr = jsonMainNode.length();  

      for(int i=0; i < lengthJsonArr; i++) {
                    /****** Get Object for each JSON node.***********/
                    JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);

                    /******* Fetch node values **********/
                    int project_id        = Integer.parseInt(jsonChildNode.optString("ID_PROJECT").toString());
                    String project_name   = jsonChildNode.optString("NM_PROJECT").toString();
                    String task_name = jsonChildNode.optString("NM_TASK").toString();


                    OutputData += "Node : \n\n     "+ project_id +" | "
                                                    + project_name +" | "
                                                    + task_name +" \n\n ";

      }

      /************ Show Output on screen/activity **********/
      output.setText( OutputData );

  } catch (JSONException e) {

                e.printStackTrace();
            }

        }
    });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM