无法将字符串转换为JSONArray或JSONObject

时间:2014-05-20 07:03:15

标签: android arrays

我无法将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){                
    }
}

这是字符串结果:

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

使用此代码时,我无法获得祝酒。

1 个答案:

答案 0 :(得分:1)

这是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();
            }

        }
    });
}