Retrofit用参数数组解析Json

时间:2016-10-19 14:42:28

标签: java android json retrofit

我在使用Retrofit解析json时遇到问题无法获取任何数据,这个URL请求参数数组 https://lao.busnavi.asia/api/location.php?ids%5B%5D=132&ids%5B%5D=133&ids%5B%5D=131

来自服务器的JSON,看起来像这样 json data

我的代码

LatestBusLocation.java

@SerializedName("id") private int id;
@SerializedName("status") private int status;
@SerializedName("route_id") private String routeId;
@SerializedName("lng") private double lng;
@SerializedName("lat") private double lat;
@SerializedName("accuracy") private double accuracy;
@SerializedName("speed") private double speed;
@SerializedName("heading") private float heading;
@SerializedName("date") private Date date;

接口类

public interface ApiService {
@POST("location.php")
Call<LatestBusLocation> loadLatestBusLocation(@Query("ids[]") int[] ids);

}

MainActivity.java

int[] ids = {131, 132, 133};

    Call<LatestBusLocation> call = HttpManager.getInstance()
            .getService().loadLatestBusLocation(ids);
    call.enqueue(new Callback<LatestBusLocation>() {
        @Override
        public void onResponse(Call<LatestBusLocation> call, Response<LatestBusLocation> response) {

            Log.e("WorkOrNote1", "Working");
            if (response.isSuccessful()) {
                dao = response.body();
                Log.d("daoResponse", String.valueOf(dao.getId()));

            } else {
                try {
                    Log.e("LatestBusLocation", response.errorBody().string());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onFailure(Call<LatestBusLocation> call, Throwable t) {
            Log.e("onFailure", t.toString());
        }
    });

1 个答案:

答案 0 :(得分:0)

由于您在LatestBusLocation中指定了Call,因此改造无法映射您的对象。这应该是List<LatestBusLocation>

另外,您必须添加一个反序列化器来正确映射,因为您正在获取一个对象(使用ids键)而不是正确的数组。看this relationed answer