如何使用改型获得(@GET)JSON数组响应

时间:2019-02-20 09:05:59

标签: php android json retrofit retrofit2

我正在开发一个使用REST API进行数据交换的应用程序。我的后端脚本是PHP,在我的一个模块中,我将作为后端的JSON响应进行发送 到Android客户端,并使用带有@GET批注的改型在Android端获取。

下面是我要接受的JSON。

[
    [
        {
            "column_name": "email"
        },
        {
            "column_name": "product_code"
        }
    ],
    [
        {
            "column_value": "ht@t.com"
        },
        {
            "column_value": "BBAN0003"
        }
   ]
]    

下面是我的改造界面,

@GET("testing/getProductdetails.php") 
Call<JSONArray> getColumnNames(@Query("email") String email);

我遇到的错误是

  

预期为begin对象,但为begin数组

我的PHP后端代码

<?php 

 /*
 * Created by Belal Khan
 * website: www.simplifiedcoding.net 
 * Retrieve Data From MySQL Database in Android
 */

 //database constants
 define('DB_HOST', 'localhost');
 define('DB_USER', 'id6935081_pksinghhps');
 define('DB_PASS', 'kingmessi10');
 define('DB_NAME', 'id6935081_users');

 //connecting to database and getting the connection object
 $conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);

 //Checking if any error occured while connecting
 if (mysqli_connect_errno()) {
 echo "Failed to connect to MySQL: " . mysqli_connect_error();
 die();
 }
 if(isset($_GET['email']))
{
     $email=$_GET["email"];

 $sql = "SHOW COLUMNS from product_details";
if (($result = $conn->query($sql)) == true) {
    while ($row = $result->fetch_array()) {
        $sub[] = $row[0];


    }
}
      $column_value = array();

      $sql2 = "SELECT * FROM product_details WHERE email = '".$email."' ";
       if (($result2 = $conn->query($sql2)) == true) {
           while($row2 = $result2->fetch_array()){
          for($j=0;$j<sizeof($sub);$j++){
           $sub2 = array();    
           $sub2["column_value"] = $row2[$j];
           array_push($column_value,$sub2);
          }

       }
       }

       else echo "NO";


 $events = array(); 
 $k=0;
 while($k<sizeof($sub)){
     $temp = array();
     $temp['column_name']= $sub[$k];
     array_push($events, $temp);
     $k++;

 }


     $main = array();
     array_push($main,$events);
     array_push($main,$column_value);
     echo json_encode($main);


}
?>

2 个答案:

答案 0 :(得分:0)

只需更改

Call<List<List<Map>>>

答案 1 :(得分:0)

保存您的实际数据的实体:

class JsonColumnNameHolder {
    @SerializedName("column_name")
    private final String myField;
    @SerializedName("column_value")
    private final String myField2;

    public JsonColumnNameHolder(String myField, String myField2) {
        this.myField = myField;
        this.myField2 = myField2;
    }

    public String getName() {
        return myField;
    }

    public String getValue() {
        return myField2;
    }
}

改装签名:

@GET("testing/getProductdetails.php") 
Single<List<List<JsonColumnNameHolder>>> getColumnNames(@Query("email") String email);