douxia2053 2016-12-28 11:01
浏览 64
已采纳

改进POST请求并检索json编码结果

I have google it this issue but i'm not able to find the solution. I think guys you can help me to sort out the issue.

I am using retrofit library first time .

My issue is while i am posting the request through retrofit. i am getting below error

D/onFailure: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 1 path $

**main activity **

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.util.Date;
import java.util.List;

import retrofit.Call;
import retrofit.Callback;
import retrofit.GsonConverterFactory;
import retrofit.Response;
import retrofit.Retrofit;

public class MainActivity extends AppCompatActivity {
    String url = "http://www.example.com/App/";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        getRetrofitObject();
    }

    void getRetrofitObject() {

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(url)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        RetrofitObjectAPI service = retrofit.create(RetrofitObjectAPI.class);

         Call<List<district>> call = service.getDistrictDetails("mdistrict","search");

        call.enqueue(new Callback<List<district>>() {
            @Override
            public void onResponse(Response<List<district>> response, Retrofit retrofit) {

                try {
                    //Log.e("response---",response.toString());
                    List<district> StudentData = response.body();
                   // Log.e("StudentData---",StudentData.toString());
                } catch (Exception e) {
                    Log.d("onResponse", "There is an error");
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(Throwable t) {
                Log.d("onFailure", t.toString());
            }
        });
    }
}

RetrofitObjectAPI

import java.util.List;

import retrofit.Call;
import retrofit.http.Field;
import retrofit.http.FormUrlEncoded;
import retrofit.http.GET;
import retrofit.http.POST;
import retrofit.http.Query; 

public interface RetrofitObjectAPI {
    @FormUrlEncoded
    @POST("/kwa/api/")
   // Call<List<district>> getDistrictDetails( );
    Call<List<district>> getDistrictDetails(@Field("target") String target, @Field("action") String action);
}

Gradle

compile 'com.squareup.retrofit:retrofit:2.0.0-beta2'
compile 'com.google.code.gson:gson:1.7.2'
compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2'
compile 'com.squareup.okhttp:okhttp:2.4.0'

my php code

<?php 
$_errAry = array("status"=>400, "success"=>"false", "message"=>"Can't Service your request ","data"=>array());
$_sucAry = array("status"=>200, "success"=>"true", "message"=>"","data"=>array());

//echo json_encode($_POST);

include_once 'database.php';

// get database connection
$database = new Database();
$db = $database->getConnection();

if(!isset($_POST["target"],$_POST["action"])){echo json_encode($_errAry);exit(0);}

// instantiate Common Objects
include_once 'objects/common.class.php';
include_once 'objects/validate.php';
$_tbl=""; $_cols="";  $_ord=""; //$_whr=" AND sr_status ='0' ";
$_whr="  ";
$_max_date = (isset($_POST["max_date"])) ? $_POST["max_date"] : "";
$_max_id = (isset($_POST["max_id"])) ? (int)$_POST["max_id"] : "";
$_imei = (isset($_POST["imei"])) ? $_POST["imei"]: "";

if($_POST["target"]=="mdistrict" && $_POST["action"]=="search"){
    $_comm = new Common($db); 
    $_stmt = $_comm->readAll("master_district", "sr_id,sr_name", $_whr , " 1 asc "); 
    $_data = array();

    while ($_row = $_stmt->fetch(PDO::FETCH_ASSOC)){
        $_tmpAry = array(
                    "sr_id"=> $_row["sr_id"],
                    "sr_name"=> trim($_row["sr_name"])
                    );
    $_data[] = $_tmpAry;
    }
    $_op = $_sucAry;
    $_op["data"]=$_data;
    echo json_encode($_op);
    exit(0);
}

$_max_date = (isset($_POST["max_date"])) ? $_POST["max_date"] : "";
$_max_id = (isset($_POST["max_id"])) ? (int)$_POST["max_id"] : "";
$_imei = (isset($_POST["imei"])) ? $_POST["imei"]: "";
?>

Can anyone please help me to solve this issue. Please find where i done the mistakes

MY result json

{"status":200,"success":"true","message":"","data":[{"sr_id":"1","sr_name":"ALAPPUZHA"},{"sr_id":"2","sr_name":"KOTTAYAM"}]}
  • 写回答

2条回答 默认 最新

  • duanji9378 2016-12-28 11:42
    关注

    Your code expects to have a List as response, but your response is an object, that's why it throws error.

    You have to introduce new object which will wrap your list.

    e.g.

    class ApiResponse<T> {
        int status;
        String success;
        String message;
        T data;
    }
    

    RetrofitObjectAPI

    public interface RetrofitObjectAPI {
        @FormUrlEncoded
        @POST("/kwa/api/")
       // Call<List<district>> getDistrictDetails( );
        Call<ApiResponse<List<district>> getDistrictDetails(@Field("target") String target, @Field("action") String action);
    }
    

    Usage

    Call<ApiResponse<List<district>>> call = service.getDistrictDetails("mdistrict","search");
    call.enqueue(new Callback<ApiResponse<List<district>>>>() {
        @Override
        public void onResponse(Response<ApiResponse<List<district>>> response, Retrofit retrofit) {
    
            try {
                //Log.e("response---",response.toString());
                ApiResponse<List<district>> apiResponse = response.body();
                List<district> StudentData = apiResponse.data;
               // Log.e("StudentData---",StudentData.toString());
            } catch (Exception e) {
                Log.d("onResponse", "There is an error");
                e.printStackTrace();
            }
    
        }
    
        @Override
        public void onFailure(Throwable t) {
            Log.d("onFailure", t.toString());
        }
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 删除虚拟显示器驱动 删除所有 Xorg 配置文件 删除显示器缓存文件 重启系统 可是依旧无法退出虚拟显示器
  • ¥15 vscode程序一直报同样的错,如何解决?
  • ¥15 关于使用unity中遇到的问题
  • ¥15 开放世界如何写线性关卡的用例(类似原神)
  • ¥15 关于并联谐振电磁感应加热
  • ¥60 请查询全国几个煤炭大省近十年的煤炭铁路及公路的货物周转量
  • ¥15 请帮我看看我这道c语言题到底漏了哪种情况吧!
  • ¥66 如何制作支付宝扫码跳转到发红包界面
  • ¥15 pnpm 下载element-plus
  • ¥15 解决编写PyDracula时遇到的问题