首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Gson多态json解析改进2

使用Gson多态json解析改进2
EN

Stack Overflow用户
提问于 2016-10-19 16:17:27
回答 1查看 750关注 0票数 1

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

代码语言:javascript
复制
{
"Information": {
"Id": "2dbc0dad8df94f7de7b63d8f22a03c8f",
"Type": "User",
"Name": "ASD",
"IsInProgress": false
},
"Errors": []
}

但有时反应是这样的:

代码语言:javascript
复制
{
"Information": {
"Id": "2dbc0dad8df94f7ca6b66d5f22a03c8f",
"Type": "Organization",
"Name": "ASD",
"City": "London"
"Street": "Wall street"
},
"Errors": []
}

我想用Retrofit 2+ Gson来解析它。我创建了自己的自定义多态转换器工厂:

代码语言:javascript
复制
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:

代码语言:javascript
复制
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的子类。但是我不知道如何解析对我的用户或组织模型的响应。

EN

回答 1

Stack Overflow用户

发布于 2016-10-19 17:49:59

使用retrofit2+Gson解析响应,如下所示:

代码语言:javascript
复制
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:

代码语言:javascript
复制
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:

代码语言:javascript
复制
 interface HttpApi {

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

}

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40125783

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档