从 http get 请求"Malformed JSON"



我在URL上得到了一些数据。这是我的服务器脚本:

    $db = null;
$results = "{}";
require_once("connect.php");
/* Query */
if($db != null) {
    $stmt = $db->prepare("SELECT category, category_color FROM categories ORDER BY category");
    $stmt->execute();
    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
/* Close db connection */
$db = null;
echo json_encode($results);

Sooo。。我在我的安卓应用程序上获取这些数据。这是我的应用程序从脚本中得到的:

    [{"category":"Animals","category_color":"green"},
{"category":"Art","category_color":"orange"},
{"category":"Sport","category_color":"blue"},
{"category":"Video games","category_color":"red"}]

还有我的应用程序代码,用来获取我的数据(这是我的第一个应用程序,所以在互联网上找到的一些代码帮助了我):

 @Override
protected String doInBackground(String... urls) {
    String url = urls[0];
    String parsedString;
    HttpURLConnection c = null;
    try {
        URL u = new URL(url);
        c = (HttpURLConnection) u.openConnection();
        c.setRequestMethod("GET");
        c.setRequestProperty("Content-type", "application/json");
        c.setRequestProperty("Content-length", "0");
        c.setUseCaches(false);
        c.setAllowUserInteraction(false);
        c.setConnectTimeout(this.timeout);
        c.setReadTimeout(this.timeout);
        c.connect();
        int status = c.getResponseCode();
        switch (status) {
            case 200:
            case 201:
                //Do stuff to parse my JSON to an HashMap
        }
    } catch(IOException ex) {
        Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
    } finally {
        if (c != null) {
            try {
                c.disconnect();
            } catch (Exception ex) {
                Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    return null;
}

我尝试了很多方法来将这些数据解析为HashMap(每个元素的[category,category_color]),如下所示:

            StringBuilder sb = new StringBuilder();
        String line;
        try {
            BufferedReader r1 = new BufferedReader(new InputStreamReader(c, "UTF-8"));
            while ((line = r1.readLine()) != null) {
                sb.append(line).append("n");
            }
        } finally {
            is.close();
        }
        return sb.toString();

我每次在Stack上的每个响应都发现了这个结果。但当我尝试此代码时,我的控制台已打印出:E/JSON任务:当我尝试执行以下操作时,无法解析格式错误的JSON:"JSONObject JSON=新的JSONObject(结果);

所以,这是我的最后一个问题:

从我的php脚本中获取JSON中的HashMap的最佳方法是什么?一个简单的链接可能很有用,但目前,我找不到一个干净可行的答案。

从php脚本获取数据的最佳方法是创建数组

{
  "result": [
    {
      "category": "Animals",
      "category_color": "green"
    },
    {
      "category": "Art",
      "category_color": "orange"
    }
  ]
}

您可以通过以下脚本获得上述格式的数据

$return_arr = array();
$fetch = mysql_query("SELECT category, category_color FROM categories ORDER BY category"); 
while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {
    $row_array['category'] = $row[0];
    $row_array['category_color'] = $row[1]; 

    array_push($return_arr,$row_array);
}
echo json_encode($return_arr);

通过以下代码操作数据

JSONObject jsonObject = new JSONObject(response); // here response is what you get from php script which is shown at top 
JSONArray message = jsonObject.getJSONArray("result");
for (int i = 0; i < message.length(); i++) {
                    Model model = new Model();
                    JSONObject temp = message.getJSONObject(i);
                    String category = temp.getString("category");
                    String category_color = temp.getString("category_color");

// create array or harshmap to store all data
}

您需要使用

JSONArray json = new JSONArray(result);

因为接收到的数据是JSONArray,而不是JSONObject。

尝试JSON解析工具Gson或Jackson,它可以节省您的时间

最新更新