改造 - Json 响应可以包含不同的字段,具体取决于类型

Retrofit - Json response can contain different fields depending on type

我正在使用改装开发 API 包装器,但我在创建返回的对象 classes 时遇到问题,因为来自同一端点的某些项目可能包含不同类型的字段。

例如,基本商品的返回 JSON 可能如下所示:

{
  "name": "Box of Honed Splint Armor",
  "description": "Double-click to unpack a full set of level 50 armor.",
  "type": "Container",
  "level": 0,
  "rarity": "Masterwork",
  "vendor_value": 86,
  "game_types": [
    "Wvw",
    "Dungeon",
    "Pve"
  ],
  "flags": [],
  "restrictions": [],
  "id": 9000,
  "chat_link": "[&AgEoIwAA]",
  "icon": "https://render.guildwars2.com/file/72D04673660ECB7FD904680D487030A41106F952/63218.png",
  "details": {
    "type": "Default"
  }
}

或像这样获得更详细的项目:

{
  "name": "Strong Soft Wood Longbow of Fire",
  "description": "",
  "type": "Weapon",
  "level": 44,
  "rarity": "Masterwork",
  "vendor_value": 120,
  "default_skin": "3942",
  "game_types": [ "Activity", "Dungeon", "Pve", "Wvw" ],
  "flags": [ "SoulBindOnUse" ],
  "restrictions": [],
  "id": 28445,
  "chat_link":"[&AgEdbwAA]",
  "icon": "https://render.guildwars2.com/file/C6110F52DF5AFE0F00A56F9E143E9732176DDDE9/65015.png",
  "details": {
    "type": "LongBow",
    "damage_type": "Physical",
    "min_power": 385,
    "max_power": 452,
    "defense": 0,
    "infusion_slots": [],
    "infix_upgrade": {
      "attributes": [
        { "attribute": "Power", "modifier": 62 },
        { "attribute": "Precision", "modifier": 44 }
      ]
    },
    "suffix_item_id": 24547,
    "secondary_suffix_item_id": ""
  }
}

不同项目类型之间的详细信息字段可能有很大差异,我希望有一种简单的方法来访问与每种类型对应的字段,而包装器消费者不必将类型强制转换为特定类型的子class 的空基数 class 就像其他包装器要求的那样,就像 one of the best wrappers 那样。

有没有什么方法可以根据父项的类型或类似的东西来隐藏字段,这样我就可以在项目中包含所有可能的字段class?

有什么建议吗?

根据https://www.baeldung.com/retrofit

Retrofit 通过在基础 URL 上建模并使接口 return 来自 REST 端点的实体来工作。

为了简单起见,我们将通过对我们的用户 class 进行建模来获取 JSON 的一小部分,当我们收到这些值时将采用这些值:

public class User {
    private String login;
    private long id;
    private String url;
    // ...

    // standard getters an setters

}

我们可以看到我们只为这个例子取了一部分属性。 Retrofit 不会抱怨缺少属性——因为它只映射我们需要的东西,如果我们要添加不在 JSON. 中的属性,它甚至不会抱怨