【问题标题】:How to deserialize JSON using GSON to an object of different field如何使用 GSON 将 JSON 反序列化为不同字段的对象
【发布时间】:2020-04-24 04:46:55
【问题描述】:

我从 API 收到这个对象,我想用 GSON 反序列化它:

{
results: {
 clothing_items: [
  {
    id: 422,
    created_at: "2020-01-20 11:23:10 -0500",
    image: "",
    last_event_date: null,
    name: "desk",
    thumbnail: "",
    type_of: "accessories"
  }
 ],
 events: [
  {
    id: 157,
    date: "2020-01-14 09:53:00 -0500",
    image: null,
    name: ""
  }
],
looks: [

],
tags: [
  {
    id: 97,
    created_at: "2020-01-20 10:46:12 -0500",
    title: "greatest person"
  }
]
 }
}

我想将每个对象解析为一个 SearchResult POJO,其中包含 idtitle(这是 json 中的名称或标题)和 type 这是对象键,如服装_items,事件...

【问题讨论】:

  • 创建数据模型类并解析它。 Gson gson = 新 Gson(); String json = "{'name' : 'mkyong'}";职员职员 = gson.fromJson(json, Staff.class);

标签: java android json gson deserialization


【解决方案1】:

创建数据模型类并解析它。这里的 Staff 是包含名称字段的数据模型类。

Gson gson = new Gson();
String json = "{'name' : 'mkyong'}";
Staff staff = gson.fromJson(json, Staff.class);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多