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

时间:2016-12-28 11:01:53

标签: php android json post retrofit

我已经谷歌这个问题,但我无法找到解决方案。 我认为你可以帮我解决这个问题。

我第一次使用改造库。

我的问题是我通过改造发布请求。 我收到了以下错误

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

**主要活动**

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);
}

摇篮

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'

我的PHP代码

<?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"]: "";
?>

任何人都可以帮我解决这个问题。请找出我犯错的地方

我的结果json

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

2 个答案:

答案 0 :(得分:1)

您的代码希望将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);
}

用法

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 :(得分:0)

上面我做的是错误的方式。我的数据集是 ArrayList<HashMap<String, String>> 。 所以我改变了下面的编码。现在我的情况完全正常。

1 ApiClient.java类

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界面

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类

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我的活动

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());
            }

        });
    }
}

谢谢大家。