首页 > 解决方案 > 从 Android 中的 Retrofit 获取时出现 json 格式问题

问题描述

我在从 php 文件中获取 JSON 值时遇到问题。

我该如何解决?

<?php


    //If the values are not blank
    //Connecting to our database by calling dbConnect script 
    include('connection.php');

    $id =$_POST["uyeId"];

    Class UyeBilgiler{
        public $uyeAd = "";
        public $uyeYas = "";
        public $uyeOkul = "";
        public $uyeResim = "";
        public $uyeEmail = "";
    }

    $uyeBilgiler = new UyeBilgiler();

    $informationSql = "SELECT * FROM bilgiler WHERE id = '$id' ";

    $list = mysqli_query($conn,$informationSql);

    while($result = mysqli_fetch_assoc($list)){
        $uyeBilgiler->uyeAd = $result["uyeAd"];
        $uyeBilgiler->uyeYas = $result["uyeYas"];
        $uyeBilgiler->uyeOkul = $result["uyeOkul"];
        $uyeBilgiler->uyeResim = $result["uyeResim"];
        $uyeBilgiler->uyeEmail = $result["uyeEmail"];

        echo json_encode($uyeBilgiler,JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT);
    }


?>

当我给 $id 变量赋值为 1 时,json 格式的输出如下所示。

{ "uyeAd": "Ali yılmaz", "uyeYas": "29", "uyeOkul": "Ali Myo", "uyeResim": "bir.jpg", "uyeEmail": "ali@gmail.com" }

在第一个花式大括号之后和最后一个花式大括号之前有一个间隙。

对于安卓部分,

@GET("/getInformationByUyeId.php")
Call<UyeBilgiler>  bilgiGetir(@Query("uyeId") String id);

当我在不使用 $_POST["uyeId"] 的情况下手动定义 $id ($id = "1") 时,我得到一个没有任何错误的 json 文件。但是使用 $_POST["uyeId"] 会抛出一个错误,如下所示。

预期为 BEGIN_OBJECT,但在第 1 行第 1 列路径 $

标签: phpandroidjson

解决方案


像这样从您的 API 响应创建一个模型类。

@SerializedName("uyeAd")
@Expose
private String uyeAd;
@SerializedName("uyeYas")
@Expose
private String uyeYas;
@SerializedName("uyeOkul")
@Expose
private String uyeOkul;
@SerializedName("uyeResim")
@Expose
private String uyeResim;
@SerializedName("uyeEmail")
@Expose
private String uyeEmail;

并将您的响应分配给您的模型类,如下所示

if(response.isSuccessful())
  {
     modelClass = response.body();
  }

在 modelClass 中创建 getter setter mom 并从中获取值并显示在您的文本中view txt.setText("Isminiz : " + modelClass.getName());


推荐阅读