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 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 matlab有关常微分方程的问题求解决
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考