用Gson多态json解析改造2

时间:2016-10-19 08:17:27

标签: android json retrofit2 gson

我从服务器得到了这个json响应:

{
"Information": {
"Id": "2dbc0dad8df94f7de7b63d8f22a03c8f",
"Type": "User",
"Name": "ASD",
"IsInProgress": false
},
"Errors": []
}

但有时反应是这样的:

{
"Information": {
"Id": "2dbc0dad8df94f7ca6b66d5f22a03c8f",
"Type": "Organization",
"Name": "ASD",
"City": "London"
"Street": "Wall street"
},
"Errors": []
}

我想用Retrofit 2 + Gson解析这个问题。 我创建了自定义多态转换器工厂:

public class DetailConverterFactory extends Converter.Factory {

private Gson gson;
@Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {

    if (gson == null){
        final RuntimeTypeAdapterFactory<DetailInformation> typeFactory = RuntimeTypeAdapterFactory
                .of(DetailInformation.class, "Type") // Here you specify which is the parent class and what field particularizes the child class.
                .registerSubtype(User.class, "User");
.registerSubtype(Organization.class, "Organization");

        // add the polymorphic specialization
        gson = new GsonBuilder().registerTypeAdapterFactory(typeFactory).create();
    }

    TypeAdapter<?> gsonAdapter = gson.getAdapter(TypeToken.get(type));
    return new CustomResponseBodyConverter<>(gsonAdapter, gson); //super.responseBodyConverter(type, annotations, retrofit);
}

private class CustomResponseBodyConverter<T> implements Converter<ResponseBody, T>{

    private TypeAdapter<T> gsonAdapter;
    private Gson gson;

    public CustomResponseBodyConverter(TypeAdapter<T> gsonAdapter, Gson gson) {
        this.gsonAdapter = gsonAdapter;
        this.gson = gson;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {

        JsonReader jsonReader = gson.newJsonReader(value.charStream());

        try{
            return gsonAdapter.read(jsonReader);
        } finally {
            value.close();
        }
    }
}
}

我的问题是,我不知道如何使用它。 我已将自定义转换器工厂添加到我的restclient。我这样称呼我的api:

Callback<DetailModel> detailModelCallback = new Callback<DetailModel>() {
        @Override
        public void onResponse(Call<DetailModel> call, Response<DetailModel> response) {
            final DetailModel detailResponse = new RetrofitObjectExtractor<>(DetailModel.class).extract(response);

            if (detailResponse == null){
                // TODO error handling
                Log.d("ERR", " detail null :(");
            }else {
                Log.d("OK", "good");
            }
        }

        @Override
        public void onFailure(Call<DetailModel> call, Throwable t) {
            Log.d("ERR", "fail");
        }

但我的DetailModel是一个基类,我的User.class和Organization.class是DetailModel的子类。但我不知道如何解析对我的用户或组织模型的响应。

1 个答案:

答案 0 :(得分:-1)

使用retrofit2 + Gson来解析响应,就像这样:

String baseurl="http://";
    Retrofit retrofit = new Retrofit
            .Builder()
            .addConverterFactory(GsonConverterFactory.create())
            .baseUrl(baseurl)
            .build();

    HttpApi httpApi = retrofit.create(HttpApi.class);
    Call<DetailModel> call= httpApi.getData();
    call.enqueue(new Callback<DetailModel>() {
        @Override
        public void onResponse(Call<DetailModel> call, Response<DetailModel> response) {
            //todo
        }

        @Override
        public void onFailure(Call<DetailModel> call, Throwable t) {
            //todo
        }
    });

DetailModel:

public class DetailModel {

public InformationBean Information;

public List<?> Errors;

public static class InformationBean {
    public String Id;
    public String Type;
    public String Name;
    public String City;
    public String Street;
    public boolean IsInProgress;
}

}

HttpApi:

 interface HttpApi {

@GET("home")
Call<DetailModel>  getData();

}