首页 > 解决方案 > 如何修复“java.lang.String 类型的值名称无法转换为 JSONObject”

问题描述

我正在使用 Volley 在 Android 中发送 HTTP 请求,但出现此错误:

java.lang.String 无法转换为 JSONObject。

在服务器端,我使用 PHP 脚本从数据库中获取值。

我的安卓代码:

String server_url = "http://192.168.225.40/server/greetings.php";
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, server_url,null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {

                        try {
                            name.setText(response.getString("name"));
                            email.setText(response.getString("email"));
                        }
                        catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                if(firebaseUser!=null){
                    if(!firebaseUser.getEmail().isEmpty())
                    {
                        email.setText(firebaseUser.getEmail());}

                }

                error.printStackTrace();

            }
        }
        );
        singletonclasshttp.getInstance(getActivity()).addtorequestque(jsonObjectRequest);

我的 PHP 脚本:

?php
$username="root";
$password="";
$host = "localhost";
$dbname = "test";
$con = mysqli_connect($host,$username,$password,$dbname);
$sql = "select * from user where uid =1;";
$result = mysqli_query($con,$sql);
$data=array();

if(mysqli_num_rows($result)>0)
{

    $row = mysqli_fetch_assoc($result); 
    echo json_encode(array("name"=>$row["name"],"email"=>$row["email"],"type"=>$row["type"]));


}


?>

我需要解析 JSON 并设置文本字段的值。

标签: phpandroidjsonandroid-volley

解决方案


您正在获取 JsonArray。你应该使用StringRequest. 然后将 String 转换为 JsonArray 并从数组中获取 JsonObject。


推荐阅读