【问题标题】:How can I use an object inside a HashMap when parsing multidimensional JSON with GSON in JAVA?在 JAVA 中使用 GSON 解析多维 JSON 时,如何在 HashMap 中使用对象?
【发布时间】:2017-08-22 22:35:36
【问题描述】:

如果我有类似的 JSON 数据:

{
   "status":200,

   "carList":[
       {
          "carId":121,
          "carName":"Cat",
      },
      {
         "carId":122,
         "carName":"Snek",
      }
   ]
}

我想通过以下方式使用 GSON 创建对象:

Cars cars = gson.fromJson(api.response(), Cars.class);

像这样使用两个类:

Class Cars{
    public String status;
    public Hashmap<String, Car> carList;
}

Class Car{
    public String carId;
    public String carName;
}

从我正在阅读的内容来看,我的问题是将对象放入 HashMap 中。

一天结束时,我需要能够循环“carLis”以将其显示在表格中,但我不确定我的方法应该是什么。

【问题讨论】:

  • JSON 数组不会映射到 HashMap。将其更改为List&lt;Car&gt;。让您的客户生成HashMap 或单独公开它。
  • @SotiriosDelimanolis 你怎么知道什么时候像 siriraghavan 说的那样使用列表或数组列表?
  • 看我的回答here

标签: java json hashmap gson


【解决方案1】:

carList 是一个对象数组,而不是哈希图。 试试把carList的类型改成ArrayList

Class Cars{
    public String status;
    public ArrayList<Car> carList;
}

您可以遍历 ArrayList 中的元素

【讨论】:

  • 谢谢!这就是我需要做的!
猜你喜欢
  • 1970-01-01
  • 2023-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-01
相关资源
最近更新 更多