Retrofit:处理数组或单个对象的问题

时间:2015-08-10 12:19:15

标签: java android retrofit

我一直在关注其他答案,但有一个缺失的步骤,我无法找到哪个导致调用成功但数据未被正确解析,因为我做的第一个调用返回一个对象列表但只返回一个对象这都是空的

MyModel.java

    public class MyModel {
        @SerializedName("url")
        private String mUrl;

        @SerializedName("name")
        private String mName;

        @SerializedName("description")
        private String mDescription;
    }

MyModelDeserializer.java

这只是检查它的数组或对象是否只返回数组

public class MyModelTypeAdapter implements JsonDeserializer<ArrayList<MyModel>>{

    @Override
    public ArrayList<MyModel> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
            ArrayList<MyModel> objects = new ArrayList<>();
            if(json.isJsonArray()){
                for(JsonElement e : json.getAsJsonArray()){
                    objects.add((MyModel)context.deserialize(e,MyModel.class));
                }
            }else if(json.isJsonObject()){
                objects.add((MyModel)context.deserialize(json,MyModel.class));
            }
        return objects;
    }
}

其他一些东西

 Gson gson = new GsonBuilder()
                    .registerTypeAdapter(new TypeToken<ArrayList<MyModel>>() {}.getType(), new MyModelTypeAdapter())
                    .create();
 restAdapter = new RestAdapter.Builder()
                    .setEndpoint(BuildConstants.BASE_URL)
                    .setConverter(new GsonConverter(gson))
                    .setClient(new OkClient(okHttpClient))
                    .setLogLevel(RestAdapter.LogLevel.FULL)
                    .build();

这是令我困惑的部分,我将什么作为回调的返回类型

@GET(URLConstants.LIST_URL)
    void getData(Callback<ArrayList<MyModel>> callback);

编辑JSON数据

{
  "places": [
    {
      "url": "www.google.com",
      "name": "Google",
      "description": "Search engine"
    },
    {
      "url": "www.Facebook.com",
      "name": "Facebook",
      "description": "Social Network"
    },

    {
      "url": "www.amazon.com",
      "name": "Amazon",
      "description": "Shopping"
    }
]
  }

1 个答案:

答案 0 :(得分:1)

首先创建一个POJO类来处理json。您可以使用jsonschema2pojo为json创建pojo类:

public class MyModel {

    @Expose
    private List<Place> places = new ArrayList<Place>();

    /**
     *
     * @return
     * The places
     */
    public List<Place> getPlaces() {
        return places;
    }

    /**
     *
     * @param places
     * The places
     */
    public void setPlaces(List<Place> places) {
        this.places = places;
    }

}

public class Place {

    @Expose
    private String url;
    @Expose
    private String name;
    @Expose
    private String description;

    /**
     *
     * @return
     * The url
     */
    public String getUrl() {
        return url;
    }

    /**
     *
     * @param url
     * The url
     */
    public void setUrl(String url) {
        this.url = url;
    }

    /**
     *
     * @return
     * The name
     */
    public String getName() {
        return name;
    }

    /**
     *
     * @param name
     * The name
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     *
     * @return
     * The description
     */
    public String getDescription() {
        return description;
    }

    /**
     *
     * @param description
     * The description
     */
    public void setDescription(String description) {
        this.description = description;
    }

}

接下来创建一个这样的restadapter:

public class SimpleRestClient {

private SimpleRestApi simpleRestApi;

public SimpleRestClient() {

    RestAdapter restAdapter = new RestAdapter.Builder()
            .setLogLevel(RestAdapter.LogLevel.FULL)
            .setEndpoint(Constants.BASE_URL)
            .build();

    simpleRestApi = restAdapter.create(SimpleRestApi.class);

}

public SimpleRestApi getSimpleRestApi() {

    return simpleRestApi;

}

}

现在创建api接口。这里我们设置我们的POJO类来处理json响应:

public interface SimpleRestApi {

@GET("Enter URL")
public void getSimpleResponse(Callback<MyModel> handlerCallback);

}

最后称之为:

simpleRestApi = new SimpleRestClient().getSimpleRestApi();
    simpleRestApi.getSimpleResponse(new Callback<MyModel>() {
        @Override
        public void success(MyModel responseHandler, Response response) {
            // here you can get your url, name and description.
        }

        @Override
        public void failure(RetrofitError error) {
            progress.dismiss();
            Log.e("CLASS", "JSON: " + error.getCause());
        }
    });

参考文献:

jsonschema2pojo

A smart way to use retrofit