首页 > 解决方案 > Android 从 php 读取 JsonObject 作为字符串

问题描述

我想从我的 php 中获取我的 json 结果并在 android 中显示它,我尝试了很多解决方案,但没有什么对我有用。在android方面,我使用了JSONParser,并且总是在这个ligne中得到json = null,JSONObject json=jParser.getJSONFromUrl(url);并出现以下错误:Error parsing data org.json.JSONException: Value n of type java.lang.String cannot be converted to JSONObject

我将发布我的 php 代码,因为我的 android 代码我确信它可以正常工作,因为我使用 codeigniter 框架使用另一个 php 代码对其进行了测试。

function get_user($id = 0) {
  global $connection;
  $query = "SELECT * FROM users";
  if ($id != 0) {
    $query. = "WHERE id =".$id. "LIMIT 1";
  }
  $response = array();
  $result = mysqli_query($connection, $query);
  while ($row = mysqli_fetch_array($result)) {
    array_push($response, array("id" => $row['id'], "username" => $row['username']));
  }
  header('Content-Type: application/json');
  echo json_encode(array('user' => $response));
  mysli_close($connection);
}

执行我的网址时的结果是:

{
  "user": [
    {
        "id": "1",
        "username": "myusername"

    }
  ]
}

标签: phpandroidjson

解决方案


推荐阅读