如何将json值转换为键?基本上我想使用一个键的值作为“键”和其他的值作为值

问题描述

我正在用 java spring boot 编写 API。我正在使用以下 json 作为来自另一个 API 的响应

[
  {
  "item": "Apple","count": 30
  },{
  "item": "Orange","count": 10
  },{
  "item": "Guava","count": 4
  }
]

我想把它转换成

{
  "Apple": 30,"Orange": 10,"Guava": 4
}

最简单有效的方法是什么?

解决方法

定义一个类来保存一个项目

public record Item {
    String item;
    int count;
}

使用您最喜欢的 json 库(我的是 Jackson)反序列化为 List<Item>

收集到地图:

Map<String,Integer> map = list.stream().collect(toMap(Item::getItem,Item::getCount));