简体   繁体   English

如何将对象数组保存为 HashMap?

[英]How to save Object Array as HashMap?

I have an object as,我有一个对象,

{
    "code": 0,
    "data": [
        {
            "id": 71,
            "product_id": 1
        },
        {
            "id": 72,
            "product_id": 3
        }
    ]
}

I want to save this data Array as Hashmap.我想将此data数组保存为 Hashmap。 How I can convert this easily without using a loop.我如何在不使用循环的情况下轻松转换它。

Now I am doing like,现在我正在做,

        HashMap<String, String> map = new HashMap<String, String>();
        for(Data data: dataArray){
            map.put("id", String.valueOf(data.getId()));
            map.put("product_id",String.valueOf(data.getName()));
        }

Create a class like this创建一个这样的类

public class Data {
    int id,product_id;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getProduct_id() {
        return product_id;
    }

    public void setProduct_id(int product_id) {
        this.product_id = product_id;
    }
}

This is mapped to your data json Array.这映射到您的数据 json 数组。 and then create and add to hashmap like this然后像这样创建并添加到哈希图

Data data = new Data();
data.setId(1);
data.setProduct_id(123);
List<Data> dataList = new ArrayList<>();
dataList.add(data);
HashMap<String,List<Data>> hashMap = new HashMap<>();
hashMap.put("<this-should-be-your-key>",dataList);

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

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