通过Retrofit和GSON将复杂的JSON映射为Java对象的正确方法 [英] Proper way to map complex JSON as a Java object with Retrofit and GSON

查看:219
本文介绍了通过Retrofit和GSON将复杂的JSON映射为Java对象的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果从REST API获得的JSON对象具有以下结构:

  {

IsError:false,

结果:{key1:value,key2:value,...}

}

应该组合两个不同的Java类(IsError和Result) 2016年10月06日更新:



预计在电话中使用的对象<?>?



正确使用Retrofit2在新问题中询问

$ b $如果你的所有服务都要用这个结构响应,那么我会实现一个通用类,它包含 IsError c $ c>和结果

  public class Response< T> {
private boolean IsError;
私人T结果;

// getters
}

然后对于每项服务将不得不使用相应的类,例如响应< MyClass1> 响应< MyClass2> 等作为调用<>

If the JSON Object I'm getting from the REST API has the following structure:

{

"IsError":false,

"Result":{ "key1":"value", "key2":"value", ... }

}

Should two different Java classes (IsError and Result) be composed or only one including both, as the expected Object in the Call<>?

Update 06th October 2016:

Proper usage with Retrofit2 asked in a new question

解决方案

If all your services are going to respond with that structure, then I would implement a generic class that includes both IsError and Result:

public class Response<T> {
    private boolean IsError;
    private T Result;

    // getters
}

Then for each service you would have to use the corresponding classes, e.g. Response<MyClass1>, Response<MyClass2>, etc. as the expected object in the Call<>.

这篇关于通过Retrofit和GSON将复杂的JSON映射为Java对象的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆