【问题标题】:Retrofit map json variable to keyword将 json 变量改造为关键字
【发布时间】:2014-08-11 11:51:54
【问题描述】:

因此,我正在使用具有名为“public”的变量的 API 进行改造。我将如何让它像所有其他变量一样自动映射。

例子:

@GET("/?filter=my_images")
void getMyImages(
        @Query("client_id") String id,
        @Query("api_key") String key,
        Callback<ImageList> callback
);
public static class Image{
    int id;
    String name;
    String distribution;
    String slug;
    // Can't do this:
    boolean public;
}

public static class ImageList{
    String status;
    List<Image> images;
}

示例 API 结果(json):

{
  "status": "OK",
  "images": [
    {
      "id": 1,
      "name": "My first snapshot",
      "distribution": "Ubuntu",
      "slug": "ubuntu-12.10-x32",
      "public": true
    },
    {
      "id": 2,
      "name": "Automated Backup",
      "distribution": "Ubuntu"
    }
  ]
}

【问题讨论】:

    标签: android gson retrofit


    【解决方案1】:

    Retrofit 使用 Gson 对 JSON 进行序列化。

    Gson 提供了一个@SerializedName 注释,以更改字段或方法映射到的键。您可以使用它来处理您的保留字:

    @SerializedName("public")
    public String isPublic;
    

    【讨论】:

    • 工作就像一个魅力。我是处理注释的新手,所以我忘记检查类似的东西。这也将有助于摆脱那些带有下划线的丑陋非标准变量。
    • @JaySee 您可能还会在创建GsonConverter 时查看setFieldNamingPolicy/setFieldNamingStrategy 选项 - 这些可用于自动将带下划线的 JSON 映射到驼峰式属性名称(反之亦然) -versa)
    • 嗨,Jake,Square 的人能否就这个问题给出一些提示:stackoverflow.com/questions/24467416/… ?
    【解决方案2】:

    请看这个link,如果每个键中都有下划线,这是一个更简洁的解决方案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-10
      • 2019-12-01
      • 2013-08-06
      • 1970-01-01
      • 2017-04-13
      • 1970-01-01
      相关资源
      最近更新 更多