【问题标题】:JSONException while attempting to retrieve data from database尝试从数据库中检索数据时出现 JSONException
【发布时间】:2023-03-17 17:50:02
【问题描述】:

我正在尝试从我的数据库中检索数据。我向这个 PHP 文件发送一个请求:

<?php

    require "init.php";

    $qrcode = $_POST["qrcode"];

    $sql = "select * from cespite where QrCode = $qrcode;";

    $result = mysqli_query($con, $sql);

    if(mysqli_num_rows($result)==0)
    {
        $code = "reg_failed";
        $message = "Nessun risultato trovato!";

        $err = array("code"=>$code, "message"=>$message);
        echo json_encode($err);
    }
    else
    {
        $row = $result->fetch_all(MYSQLI_ASSOC)[0];
        echo json_encode($row);
    }

    //$mysqli_close($con);

?>

这是我将请求发送到该文件的代码:

final JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response)
            {
                try
                {
                    Nome.setText(response.getString("Nome"));
                    Descrizione.setText(response.getString("Descrizione"));
                    Numinventario.setText(response.getString("NumInventario"));
                    Foto.setText(response.getString("Foto"));
                    Dtcatalogazione.setText(response.getString("DtCatalogazione"));
                }
                catch (JSONException e)
                {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                int j = 21;
            }
        })
        {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<>(1);
                params.put("qrcode", richiesta);

                return params;
            }
        };

        RegisterRequest.getmInstance(this).addToRequestque(request);

这是我的RegisterRequest 班级:

public class RegisterRequest
{
    private static RegisterRequest mInstance;
    private RequestQueue requestQueue;
    private static Context mCtx;
    //default constructor
    private RegisterRequest(Context context)
    {
        mCtx=context;
        requestQueue=getRequestQueue();
    }

    public RequestQueue getRequestQueue()
    {
        if(requestQueue==null)
        {
            requestQueue = Volley.newRequestQueue(mCtx);
        }
        return requestQueue;
    }

    public static synchronized RegisterRequest getmInstance(Context context)
    {
        if(mInstance==null)
        {
            mInstance = new RegisterRequest(context);
        }
        return mInstance;
    }

    public void addToRequestque(Request request)
    {
        requestQueue.add(request);
    }

}

我已尝试使用我的调试器。我总是在 onErrorResponse 方法中完成,我不知道为什么,因为我试图从 web 向我的 PHP 文件发送请求并且它工作正常,所以我认为这可能是发送参数的问题到请求。 我得到的错误是Value &lt;br of type java.lang.String cannot be converted to JSONObject

有什么办法吗?

提前致谢!

编辑:解决了发出字符串请求而不是 jsonobject 请求

【问题讨论】:

  • 我认为您请求的 URL 错误。
  • @VladMatvienko 不,这是正确的-_-'
  • 使用 PostMan 检查响应
  • 错误说你得到的是HTML而不是JSON,所以我仍然认为它是不正确的。或者你没有把你的 PHP 文件放在正确的位置。或者 PHP 不正确。首先通过浏览器或任何其他 HTTP 工具检查您是否会收到 JSON 作为响应。

标签: php android mysql json


【解决方案1】:

您的 PHP 脚本中发生错误,导致输出如下所示:

ERROR AT LINE X: INFORMATION ABOUT THE ERROR

{"code": "code", "message": "Something went wrong"}

这会导致整体输出为无效 JSON(因为第一个 ERROR 行不是 JSON)。这会导致您收到 JSON 异常。尝试通过例如使用标准文本请求而不是 JSONRequest 与其联系来验证您的 PHP 脚本是否正常工作。这样,您应该会看到发生的 PHP 错误。您也可以尝试查看您的服务器日志,看看那里是否有任何有用的信息。

另外说明,您的 PHP 脚本容易受到 SQL 注入攻击。尝试看看如果将 $_POST['qrcode'] 的值替换为引号(例如: ' )会发生什么。这样,有恶意的人就可以掌握您的整个数据库。您可以使用准备好的语句来解决此问题。

【讨论】:

  • 我已经用一个简单的文本请求尝试了我的 php,它可以工作;我不知道为什么使用 Json 请求它不起作用
  • @Interseba5 哦,我明白了你的问题,你的 json 包含 "alldata": [{"Nome": .... }] 但在你的 java 中你假设它只包含 {"Nome": .... }
【解决方案2】:

尝试制作正确的 jsonObject

if(mysqli_num_rows($result)==0)
{

$array = array();

$array[] = "reg_failed";
$array[] = "reg_failed";"Nessun risultato trovato!";

$get = array("error" => $array);

header('Content-type: application/json');
echo json_encode($get);
}else{

$array = array();
while($row = mysqli_fetch_assoc($result))
{
$array[] = $row;
}
$get = array("alldata" => $array);

header('Content-type: application/json');
echo json_encode($get);

}

这里是解析 jsonObject 的 java 代码

JSONArray jsonArray = response.getJSONArray("alldata");

JSONObject jsonObj = jsonArray.getJSONObject(0);

if (jsonObj.getString("Nome") != null) {

Nome.setText(jsonObj.getString("Nome"));
Descrizione.setText(jsonObj.getString("Descrizione")); 
Numinventario.setText(jsonObj.getString("NumInventario"));
Foto.setText(jsonObj.getString("Foto"));
Dtcatalogazione.setText(jsonObj.getString("DtCatalogazione"));
}

如果您还有问题,请告诉我

【讨论】:

  • 没有人同样的问题.. 看看 php 输出:imgur.com/L2O1qVj Android Studio 中的错误:imgur.com/D0PuHy4
  • 现在您以错误的方式解析 jsonObject。给我看看你在 android Studio 中使用的解析代码
  • 这里是请求类:imgur.com/cFhBtx2 ShowData 活动(我发送请求的地方):imgur.com/4ma9OP7imgur.com/L0qtSqO
  • 您的解析代码有问题。让我更新答案。
  • 解决了发出字符串请求而不是 jsonobject 请求,谢谢!
猜你喜欢
  • 1970-01-01
  • 2013-04-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多