0

我遇到了字符串无法转换为 JSONObject 的问题。有人可以帮助解决这个问题吗?感谢并非常感谢您的帮助。

protected void onPostExecute(String result) {           
if (result==null || result.length()==0){
            // no result:
            return;
}

//clear the list
moviesList.clear();

try {
    //turn the result into a JSON object
    JSONObject responseObject = new JSONObject("results");

            // get the JSON array named "results"
    JSONArray resultsArray = responseObject.getJSONArray(result);

    // Iterate over the JSON array: 
    for (int i = 0; i < resultsArray.length(); i++) {
        // the JSON object in position i 
        JSONObject messageObject = resultsArray.getJSONObject(i);

    // get the primitive values in the object
        String title = messageObject.getString("title");
        String details = messageObject.getString("synopsis");

        //put into the list:
            Movie movie = new Movie(title, details, null,null);
        moviesList.add(movie);
    }
    } catch (JSONException e) {
        e.printStackTrace();
    }

    //refresh listView:
    adapter.notifyDataSetChanged();

    }
} 

结果有价值

错误在以下行:

JSONObject responseObject = new JSONObject("results");
4

4 回答 4

1
    String obj=JSONObject.quote(YourData);
    JSONArray lArray=new JSONArray(obj);

    // or simply  Delete the prefix 'results'  from your php Code
    // $res2=array("results"=>$response);
    // and you will retrive directelly your JsonArray like 

    JSONArray lArray=new JSONArray(YouData);
于 2013-11-12T23:23:11.433 回答
0

看起来你只是混淆了这两行,试试这种方式:

//turn the result into a JSON object
JSONObject responseObject = new JSONObject(result);

// get the JSON array named "results"
JSONArray resultsArray = responseObject.getJSONArray("results");

这是假设您从某处获得的 JSON 响应包含一个 JSONObject,而后者又在“结果”中包含一个 JSONArray。

从您的代码示例中的注释来看,情况就是这样,这只是由于命名相似而简单混淆的情况。

于 2013-11-13T00:24:52.737 回答
0
  • 那是因为你的格式JSONObject是错误的。请参阅 如何在 Java 中将 String 转换为 JSONObject 。只是"results"不是一个JSON。尝试并拥有类似的东西:

    {"result":"blahblah"}

  • result或者你在写作时错误地包含了双引号

    JSONObject responseObject = new JSONObject("results");

    由于result已经是一个字符串,请尝试将该行替换为:

    JSONObject responseObject = new JSONObject(results);

于 2013-11-12T23:22:17.733 回答
0

检查 JSON 字符串本身是否以 [ 例如

[{"hello":"goodbye","name":"bob","age":26}]

如果这样做,这意味着它不是 JSONObject 而是 JSONArray。尝试改变

JSONObject responseObject = new JSONObject("results");

        // get the JSON array named "results"
JSONArray resultsArray = responseObject.getJSONArray(result);

类似于

JSONArray responseArray = new JSONArray("results");
JSONObject resonseObject = responseArray.toJSONObject(responseArray);
于 2013-11-28T07:03:57.033 回答