【问题标题】:How to deserialize json to nested custom map via gson?如何通过 gson 将 json 反序列化为嵌套的自定义地图?
【发布时间】:2021-12-24 05:48:36
【问题描述】:

我有以下 json

{
  "id": "1111",
  "match": {
    "username1": {
      "id": "1234",
      "name": "alex"
    },
    "username2": {
      "id": "5678",
      "name": "munch"
    }
  }
}

为了反序列化它,我有以下数据模型类..

class json{
    String id;
    Match match;
}

class Match {  
  private Map<String,Profile> profiles  
}

class Profile{
    private String id;
    private String name;
}

我在使用 gson 时没有收到任何反序列化错误,但是 profiles 变量为空。 这就是我反序列化的方式 var json = gson.fromJson(data,json.class)

match 对象中可以有动态的用户名数量,而不仅仅是两个。为什么我将 profile 对象设为 null,如何正确填充它?

更改 json 是这里的最后手段。我可以进行任何其他所需的更改。

【问题讨论】:

  • Profile有二传手吗?
  • @JoãoDias 是的,我确实有标准的 getter 和 setter。

标签: java json jackson gson


【解决方案1】:

问题在于您的型号。您不需要Match,因为profiles 在您的JSON 中并不真正存在。你只需json(这个有小改动)和Profile

class json{
    String id;
    Map<String,Profile> match;
}

这会起作用。

【讨论】:

  • 非常感谢!像魅力一样工作。
  • 不客气 ;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-20
  • 2011-08-31
  • 2016-02-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多