【问题标题】:How to fix 'Value name of type java.lang.String cannot be converted to JSONObject'如何修复“java.lang.String 类型的值名称无法转换为 JSONObject”
【发布时间】:2019-06-13 18:07:19
【问题描述】:

我正在使用 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 并设置文本字段的值。

【问题讨论】:

  • 发布您的响应类和 gson 响应

标签: php android json android-volley


【解决方案1】:

使用this站点从json响应生成正确的响应类

【讨论】:

  • 感谢您的回复。错误是由于我的代码中的拼写错误造成的。
  • 很高兴听到这个消息。随时投票并接受我的回答。
【解决方案2】:

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

【讨论】:

  • 感谢您的回复。错误是由于我的代码中的拼写错误造成的。
猜你喜欢
  • 1970-01-01
  • 2017-02-03
  • 2017-10-02
  • 2013-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多