【问题标题】:string convert to json in android在android中字符串转换为json
【发布时间】:2016-10-07 08:10:59
【问题描述】:
    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,这样我就可以计算那里有多少条记录。但我在JSONObject json = new JSONObject(response); 行中收到Unhandled Exception: org.json.JSONException 的错误

System.out.println(response); 行将产生如下结果:

I/System.out: [{"email":"admin@gmail.com","username":"admin","password":"admin","fname":"Bradley","mname" :"Buenafe","lname":"Dalina","suffix":"","status":"1"}]

如何正确地将这种格式的String转换成JSON

【问题讨论】:

    标签: java android json


    【解决方案1】:

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

    JSONArray jsonArray = new JSONArray(response);
    

    【讨论】:

    • 我是否需要一个特定的导入,我无法提及这一点,但我已经尝试过了
    • org.json.JSONArray?
    • 使用 JSONArray 和您得到的特定异常更新您问题中的代码。
    • 用值来自的php页面更新了问题
    【解决方案2】:
    try {
         JSONArray jsonArray = new JSONArray(response);
         Log.d("Reading response: ", jsonArray.length()+"");
    } catch (JSONException e) {
         // Do something with the exception
    }
    

    我在某个地方读到了你需要放入 try catch 的内容。我做到了,它没有错误,并且还返回了正确的长度。

    我不确定这是否是解决此问题的 hackish 方式。

    【讨论】:

    • 这没有任何意义
    • 你是什么意思我现在正在使用 try catch 解决方案有什么原因会失败吗? @NielsMasdorp
    • 好吧,try catch 只捕获Exception,防止您的应用程序崩溃,但它不会阻止实际的Exception 被抛出。
    【解决方案3】:

    我对 JSON 了解不多,但是当我不得不使用它时,我从 google 调用了一个 github 模式。 Gson - https://github.com/google/gson 您只需要获取库并添加 Maven 依赖项即可。

    完成此操作后,您可以使用 toJson() 和 fromJson() 将 Java 对象转换为 JSON 并返回。

    希望对你有帮助:)

    【讨论】:

      【解决方案4】:

      而不是:

      JSONObject json = new JSONObject(response);
      

      用途:

      JSONArray json = new JSONArray(response);
      

      正如您在 System.out 中所展示的,您得到的是 json 数组而不是 json 对象的响应。

      json数组总是以'['开头,json对象总是以'{'开头

      【讨论】:

      • 我是否需要一个特定的导入,我无法提及这一点,但我已经尝试过了
      • 与 JSONObject 类似的导入,即org.json.JSONArray。如果您仍然遇到问题,请发布最新日志,因为根据旧日志,这应该可以解决问题。
      猜你喜欢
      • 1970-01-01
      • 2013-08-14
      • 2014-01-08
      • 2014-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-28
      • 2021-09-23
      相关资源
      最近更新 更多