1

我正在阅读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 是下一个:

用户类

public class User {

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

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

    ... CONSTRUCTOR AND GETTERS/SETTERS

}

用户数据类

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?

谢谢你。

4

2 回答 2

0

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

于 2016-06-14T11:39:14.053 回答
0

检查改造文档中的示例

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

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

.addConverterFactory(GsonConverterFactory.create())

并添加到 build.gradle

com.squareup.retrofit2:converter-gson
于 2016-06-14T11:33:25.150 回答