douxia2053
2016-12-28 11:01
浏览 63

改进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());
        }
    });
    
    点赞 评论
  • dongzan2740 2016-12-29 07:20

    Above I am doing is wrong way.My data set is ArrayList<HashMap<String, String>> . so i changed the coding like below.Now it is perfectly working in my case.

    1 ApiClient.java class

    import retrofit.GsonConverterFactory;
    import retrofit.Retrofit; 
    
    public class ApiClient {
        public static final String BASE_URL = "http://www.yourdomain.com/App/";
        private static Retrofit retrofit = null;
    
    
        public static Retrofit getClient() {
            if (retrofit==null) {
                retrofit = new Retrofit.Builder()
                        .baseUrl(BASE_URL)
                        .addConverterFactory(GsonConverterFactory.create())
                        .build();
            }
            return retrofit;
        }
    }
    

    2 ApiInterface.java interface

    import retrofit.Call;
    import retrofit.http.Field;
    import retrofit.http.FormUrlEncoded;
    import retrofit.http.POST;
    
    public interface ApiInterface {
        @FormUrlEncoded
        @POST("kwa/api/index.php")
        Call<Example> getDistrictDetails(@Field("target") String target, @Field("action") String action);
    
    }
    

    3 Example.java class

    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import com.google.gson.annotations.Expose;
    import com.google.gson.annotations.SerializedName;
    
    public class Example {
    
        @SerializedName("status")
        @Expose
        private Integer status;
        @SerializedName("success")
        @Expose
        private String success;
        @SerializedName("message")
        @Expose
        private String message;
       /* @SerializedName("data")
        @Expose
        private List<Datum> data = null;*/
        @SerializedName("data")
        @Expose
        private ArrayList<HashMap<String, String>> tmpList=null;
    
        public Integer getStatus() {
            return status;
        }
    
        public void setStatus(Integer status) {
            this.status = status;
        }
    
        public String getSuccess() {
            return success;
        }
    
        public void setSuccess(String success) {
            this.success = success;
        }
    
        public String getMessage() {
            return message;
        }
    
        public void setMessage(String message) {
            this.message = message;
        }
    
        public ArrayList<HashMap<String, String>> getDatat() {
            return tmpList;
        }
    
        public void setData(ArrayList<HashMap<String, String>> data) {
            this.tmpList = data;
        } 
    }
    

    4 DemoActivity.java my activity

    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.util.Log;
    
    import com.panenviron.retrofitstudyapp.R;
    
    import org.json.JSONArray;
    
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    
    import retrofit.Call;
    import retrofit.Callback;
    import retrofit.Response;
    import retrofit.Retrofit;
    
    
    public class DemoActivity extends AppCompatActivity {
        private static final String TAG = DemoActivity.class.getSimpleName();
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            getRetrofitObject();
        }
        void getRetrofitObject() {
            ApiInterface apiService =  ApiClient.getClient().create(ApiInterface.class);
            Call<Example> call = apiService.getDistrictDetails("msection","search");
            call.enqueue(new Callback<Example>() {
                @Override
                public void onResponse(Response<Example> response, Retrofit retrofit) { 
                    ArrayList<HashMap<String, String>> tmpList = response.body().getDatat();
                    Log.e(TAG+"tmpList---", tmpList.toString());
    
    
                }
                @Override
                public void onFailure(Throwable t) {
                    Log.e(TAG+"--", t.toString());
                }
    
            });
        }
    }
    

    Thanks all.

    点赞 评论

相关推荐 更多相似问题