【问题标题】:Retrofit, top level json object changes?改造,顶级json对象变化?
【发布时间】:2016-08-21 02:41:12
【问题描述】:

我正在使用 Retrofit 进行一些 api 调用。对于特定的端点,返回的 json 看起来有点像这样:

端点:api.example.com/1.0/userinfo?userid=7

返回的响应有点像这样:

{
    "7":{
        "name":"george",
        "age"="32"
        }

} 

基本上,顶级对象是传递给 url 参数的任何数字(在本例中为 7)。

因此,当创建我的 Java 对象来对此响应建模时,我如何为这个顶级对象建模,以便即使名称发生更改,它在使用 gson 时也能正确映射?

【问题讨论】:

    标签: android json gson retrofit retrofit2


    【解决方案1】:

    界面:

    @Get
    Call<Map<String,User>> getUserInfo(@Url String url);
    

    用法:

    Map<String,User> response =getUserInfo("http://api.example.com/1.0/userinfo?userid=7");
    User user = response.get("7");
    

    “7”是userid=?

    界面:

    @Get("1.0/userinfo")
    Call<Map<String,User>> getUserInfo(@Query("userid")String userid);
    

    用法:

    String userId = "7";
    Map<String,User> response = Retrofit.Builder().baseUrl("http://api.example.com").create(ApiService.class).getUserInfo(userId).execute();
    User user = response.get(userId);`
    

    【讨论】:

    • 我不确定我是否遵循。你为什么使用Map?我以前使用过 Retrofit 十几次,但通常 json 是结构化的,因此顶级对象键是相同的。因此,例如:顶级对象将类似于"userinfo":{"id": 88},我将为带有 id 变量的 userinfo 创建一个模型类。但是由于在这种情况下顶层对象发生了变化,我该如何建模呢?
    猜你喜欢
    • 2016-08-22
    • 2023-04-11
    • 2017-12-29
    • 1970-01-01
    • 1970-01-01
    • 2014-10-16
    • 1970-01-01
    • 2016-02-13
    • 2017-09-02
    相关资源
    最近更新 更多