【问题标题】:Jackson to convert a json into a map of String and a list杰克逊将 json 转换为字符串和列表的映射
【发布时间】:2019-07-15 05:15:34
【问题描述】:

我有一个像下面这样的 json

{
  "department": [
    {
      "status": "active",
      "count": "100"
    },
    {
      "status": "active",
      "count": "300"
    }
  ],
  "finance": [
    {
      "status": "inactive",
      "count": "500"
    },
    {
      "status": "active",
      "count": "450"
    }
  ]
}

我的对象如下所示

class CurrentInfo
{
private String status;
private int count;
//getters and setters
}

我想将此 JSON 转换为 Map<String,List<CurrentInfo>>。我可以使用以下方法转换单个节点

ObjectMapper mapper = new ObjectMapper();
CurrentInfo currentinfo = mapper.readValue(jsonString, CurrentInfo.class);

有没有办法可以将前面提到的JSON直接转换成Map<String,List<CurrentInfo>>

【问题讨论】:

  • 你的地图的key 是什么? departmentfinance 和 .. ?
  • @user404 是的。你是对的

标签: java json jakarta-ee jackson objectmapper


【解决方案1】:

是的,你可以,根据上面的 JSON countString 类型不是 int

class CurrentInfo {
    private String status;
    private String count;
    //getters and setters
}

使用TypeReference将json字符串转成java对象

Map<String, List<CurrentInfo>> currentInfo = mapper.readValue(
        jsonString,
        new TypeReference<Map<String, List<CurrentInfo>>>() {});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-21
    • 2017-10-03
    • 1970-01-01
    • 2021-05-10
    • 1970-01-01
    • 1970-01-01
    • 2017-12-03
    • 1970-01-01
    相关资源
    最近更新 更多