【问题标题】:There is a json format problem while getting it from Retrofit in Android从 Android 中的 Retrofit 获取时出现 json 格式问题
【发布时间】:2019-07-23 10:25:06
【问题描述】:

我在从 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 列路径 $ 处为 STRING

【问题讨论】:

  • 显示 UyeBilgiler 和来自服务器的 Json 响应
  • 它基本上是解析问题,比如 1 任何你期望对象类型但从响应中获取字符串的变量,反之亦然
  • @Saran Sankaran 我把 UyeBilgiler 类和来自 JSON 响应的错误。
  • @Ashish 如您所见,我的 json 格式以左大括号开头。

标签: php android json


【解决方案1】:

像这样从您的 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());

【讨论】:

  • 我编辑帖子。我认为问题来自 $_POST["uyeId"]。
  • 嘿兄弟使用 $_GET["uyeId"];因为您在 getMethod() 中从 android 发送数据并在 $_POST[] 中接收数据;所以只需将其更改为 $_GET[];
猜你喜欢
  • 2017-04-08
  • 2018-10-21
  • 1970-01-01
  • 2020-07-02
  • 2019-11-18
  • 1970-01-01
  • 2014-09-14
  • 2017-05-25
  • 1970-01-01
相关资源
最近更新 更多