简体   繁体   English

在JAVA中使用GSON解析多维JSON时,如何在HashMap中使用对象?

[英]How can I use an object inside a HashMap when parsing multidimensional JSON with GSON in JAVA?

If I have JSON DATA like: 如果我有JSON DATA,例如:

{
   "status":200,

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

I want to Use GSON to create the objects by: 我想通过以下方式使用GSON创建对象:

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

Using the two classes like this: 使用如下两个类:

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

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

From what I am reading my problem is putting an object inside of the HashMap. 从我读到的内容来看,我的问题是在HashMap中放置一个对象。

At the end of the day I need to be able to loop the "carLis" to display it in a table but I am not sure what my approach should be. 最终,我需要能够循环显示“ carLis”以将其显示在表格中,但是我不确定应该采用哪种方法。

carList is an Array of Objects and not a hashmap. carList是一个对象数组,而不是哈希图。 Try changing the type of carList to ArrayList 尝试将carList的类型更改为ArrayList

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

You can loop over the ArrayList for the elements 您可以遍历ArrayList的元素

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM