如何为字符串和数组做一般值类型?

How can I do general value type for String and Array?

我需要从远程服务解析一些 JSON 数据。

请求 and/or 响应文件如下所示。

{
  "some": "...",
  "someOther": [
    "...",
    "..."
  ],
  "youDontKnow": "...",
  "mayBeThis": [
    "what"
  ]
}

我想,如您所见,值中只会有 stringarray

现在,我想知道是否有任何方法可以使用以下映射,而不是映射每个字段。

Map<String, Object> map; // each value may be string or array

这样我就可以按键获取并将值按需转换为 StringString[](或 List<String>)。

我该怎么做?

当您使用 DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY 时,您可以将所有值视为 List-s。

ObjectMapper mapper = new ObjectMapper();
mapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);


MapType mapType = mapper.getTypeFactory().constructMapType(Map.class, String.class, List.class);
Map<String, List> map = mapper.readValue(jsonFile, mapType);
System.out.println(map);

打印:

{some=[...], someOther=[..., ...], youDontKnow=[...], mayBeThis=[what]}

没有它,您可以使用创建适当类型的默认行为:

ObjectMapper mapper = new ObjectMapper();

Map<String, Object> map = mapper.readValue(jsonFile, Map.class);
System.out.println(map);

打印:

{some=..., someOther=[..., ...], youDontKnow=..., mayBeThis=[what]}

第二个解决方案需要您检查它是否是 List os String。第一个解决方案允许您将每个值都视为 List 并且您有很多简洁的解决方案。第三个选项是使用 ListString 属性创建 POJOJackson 将自动匹配和解析给定的 JSON.