如何在Java中将Json转换为集合?

时间:2018-10-15 09:35:24

标签: java json arraylist collections

我有以下json,如何将其转换为arrayList?

"data": [{
            "label": "Venezuela",
            "value": "290"
        }, {
            "label": "Saudi",
            "value": "260"
        }, {
            "label": "Canada",
            "value": "180"
        }, {
            "label": "Iran",
            "value": "140"
        }, {
            "label": "Russia",
            "value": "115"
        }, {
            "label": "UAE",
            "value": "100"
        }, {
            "label": "US",
            "value": "30"
        }, {
            "label": "China",
            "value": "30"
        }]
    }

1 个答案:

答案 0 :(得分:0)

您需要手动将其转换为迭代每个json并将其分配给一个对象,然后可以将其添加到集合中。 或者甚至可以使用Gson库来查看以下内容,gson可以将您的属性映射到Java Object。

JsonElement yourJson = mapping.get("data");
Type listType = new TypeToken<List<YourModel>>() {}.getType(); //YourModel should contains the same attributes which the json have (Exactly)

List<String> yourList = new Gson().fromJson(yourJson, listType);