字符串转换为android中的json

时间:2016-10-07 08:11:00

标签: java android json

    client.post("http://10.0.2.2/project/process/selectalluser.php", new AsyncHttpResponseHandler() {

        @Override
        public void onSuccess(String response) {
            Integer contacts = controller.getContactsCount();
            Log.d("Reading contacts: ", contacts+"");
            System.out.println("onSuccess");
            JSONArray jsonArray = new JSONArray(response);
            Log.d("Reading response: ", response.length()+"");
            System.out.println(response);
            Toast.makeText(getApplicationContext(), "MySQL DB has been informed about Sync activity", Toast.LENGTH_LONG).show();
        }

        @Override
        public void onFailure(int statusCode, Throwable error, String content) {
            System.out.println("onFailure");
            System.out.println(statusCode);
            System.out.println(error);
            System.out.println(content);
            Toast.makeText(getApplicationContext(), "Error Occured", Toast.LENGTH_LONG).show();
        }
    });

然后我的php:

$stmt = $dbh->prepare("SELECT * FROM `admin_tbl`");
                            if ($stmt->execute()) {
            $basicinfo = array();
            if ($stmt->rowCount() > 0) {
                while ($selected_row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                    $basicinfo[] = array(
                        'email' => $selected_row['email'],
                        'username' => $selected_row['username'],
                        'password' => $selected_row['password'],
                        'fname' => $selected_row['fname'],
                        'mname' => $selected_row['mname'],
                        'lname' => $selected_row['lname'],
                        'suffix' => $selected_row['suffix'],
                        'status' => $selected_row['status']);
                }
                echo json_encode($basicinfo, JSON_UNESCAPED_UNICODE);
                //return $basicinfo;
            } else {
                echo json_encode(array(
                    'error' => false,
                    'message' => "No record found!"
                ));
                exit;
            }
        }

这是我的代码我想将字符串类型的响应转换为JSON,这样我就可以计算出有多少条记录。但我在行Unhandled Exception: org.json.JSONException

中收到JSONObject json = new JSONObject(response);错误

System.out.println(response);将在以下结果中显示:

  

I / System.out:[{" email":" admin@gmail.com"," username":" admin" "密码":"管理"" FNAME":"布拉德利"" MNAME":" Buenafe"" L-NAME":" Dalina""后缀":"""状态&#34 ;: " 1"}]

如何正确地将此格式的String转换为JSON

4 个答案:

答案 0 :(得分:0)

您的回复不是JSONObject,而是JSONArray[]表示数组。普通物体不会有那些。你可以使用

JSONArray jsonArray = new JSONArray(response);

答案 1 :(得分:0)

而不是:

JSONObject json = new JSONObject(response);

使用:

JSONArray json = new JSONArray(response);

正如您在System.out中所示,您将获得响应为json数组而不是json对象。

Json数组总是以' ['和json对象总是以' {'

开头

答案 2 :(得分:0)

try {
     JSONArray jsonArray = new JSONArray(response);
     Log.d("Reading response: ", jsonArray.length()+"");
} catch (JSONException e) {
     // Do something with the exception
}

我读到了你需要放入try catch的地方。我做了,它没有错误,也返回了正确的长度。

我不确定这是解决这个问题的黑客方式。

答案 3 :(得分:0)

我对JSON知之甚少,但当我不得不使用它时,我调查了谷歌的一个github模式。 Gson - https://github.com/google/gson您只需要获取库并添加Maven依赖项。

一旦你这样做,你可以使用toJson()和fromJson()从Java对象转换为JSON并返回。

希望有所帮助:)