如何使用Retrofit2 + GSON - >有自定义对象的类?

时间:2016-06-14 10:52:02

标签: android gson retrofit2 custom-object nest-nested-object

我正在阅读stackoverflow中的另一篇文章,但我无法让它工作。

我有一个服务器返回的数据,它有下一个表单:

服务器响应

{
  "userData": {
    "username": "victor.javier",
    "email": "victor.javier@stackoverflow.com",
    "createdAt": "2016-05-11T09:55:14.720Z",
    "updatedAt": "2016-05-11T09:55:14.720Z",
    "id": "5733018274ddfad25"
  },
  "token": "SkpaNuXdzfrhiH06qGK93EH2ujM37hfk02F8o2EodYJumG"
}

我的代码POJO是下一个:

User.class

public class User {

    @SerializedName("userData")
    @Expose
    private UserData userData;

    @SerializedName("token")
    @Expose
    private String token;

    ... CONSTRUCTOR AND GETTERS/SETTERS

}

UserData.class

public class UserData {

    @SerializedName("username")
    @Expose
    private String username;

    @SerializedName("email")
    @Expose
    private String email;

    @SerializedName("createdAt")
    @Expose
    private String createdAt;

    @SerializedName("updatedAt")
    @Expose
    private String updatedAt;

    @SerializedName("id")
    @Expose
    private String id;

    ... CONSTRUCTOR AND GETTERS/SETTERS

}

我从另一个帖子中复制了下一个类以反序列化GSON。代码是:

RestDeserializer.class

public class RestDeserializer<T> implements JsonDeserializer<T> {

    private Class<T> mClass;
    private String mKey;

    public RestDeserializer(Class<T> targetClass, String key) {
        mClass = targetClass;
        mKey = key;
    }

    @Override
    public T deserialize(JsonElement je, Type type, JsonDeserializationContext jdc)
            throws JsonParseException {
        JsonElement content = je.getAsJsonObject().get(mKey);
        return new Gson().fromJson(content, mClass);

    }
}

改造实施是:

RetroFitImpl

public class UserApiImpl implements UserApi {

    @Inject
    public UserApiImpl() { }

    @Override
    public User loginUser(String identifier, String password) {
        Retrofit retrofitBuilder = getRetrofitBuilder();
        UserRetrofitApi userRetrofitApi = retrofitBuilder.create(UserRetrofitApi.class);

        LoginRequestEntity loginRequestEntity = new LoginRequestEntity();
        loginRequestEntity.setIdentifier(identifier);
        loginRequestEntity.setPassword(password);

        Call<User> call = userRetrofitApi.loginUser(loginRequestEntity);
        Response<User> response = null;
        try {
            response = call.execute();
        } catch (IOException e) {
            e.printStackTrace();
        }

        User body = null;
        if (response != null) {
            body = response.body();
        }
        return body;
    }

    private Retrofit getRetrofitBuilder() {
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();

        return new Retrofit.Builder()
                .baseUrl(BuildConfig.API_URL)
                .client(client)
                .addConverterFactory(buildGsonConverter())
                .build();
    }

    private static GsonConverterFactory buildGsonConverter() {
        GsonBuilder gsonBuilder = new GsonBuilder();

        Gson gson = new GsonBuilder()
                .registerTypeAdapter(User.class, new RestDeserializer<>(User.class, "userData"))
                .create();

        return GsonConverterFactory.create(gson);
    }
}

我在使用 buildGsonConverter 方法时出错了,因为我每次都会调用onError进行改造,所以我认为这是构建GSON时的一个问题。

任何人都可以告诉我如何解析这个以构建GSON,就像服务器的响应一样?

谢谢。

2 个答案:

答案 0 :(得分:0)

查看改装文档中的示例

http://square.github.io/retrofit/

您不需要创建自己的gson工厂

.addConverterFactory(GsonConverterFactory.create())

并添加到build.gradle

com.squareup.retrofit2:converter-gson

答案 1 :(得分:0)

你不需要自己创造一个pojo。您可以使用http://jsonschema2pojo.com创建一个pojo US ng yur服务器响应。