以下是我的JSON:
{
"-5": [
"15:D1_CHANNEL_ID_SK",
"23:D1_CALL_BEGIN_DATE",
"87:D1_CELL_ID"
],
"-4": [
"31:I_RECHARGE_AMOUNT",
"59:I_INBUNDLED_UNIT",
"60:I_DAY_NIGHT_FLAG",
"53:PD_UPSELL_PACK_ID",
"146:AON"
]
}
在上面的Json中,键也是一个变量(它不是常数)。因此,我无法使用mapper.readValue()
来解析json。
答案 0 :(得分:1)
我假设通过mapper.readValue()
,你试图在ObjectMapper的帮助下将字符串值读入类似结构的地图(可以是POJO或HashMap)。
以下代码从字符串中读取并将其转换为Map<String,Object>
。
public static void main(String[] args) throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
String data = "{\n" + " \"-5\": [\n" + " \"15:D1_CHANNEL_ID_SK\",\n" + " \"23:D1_CALL_BEGIN_DATE\",\n" + " \"87:D1_CELL_ID\"\n" + " ],\n" + " \"-4\": [\n" + " \"31:I_RECHARGE_AMOUNT\",\n" + " \"59:I_INBUNDLED_UNIT\",\n" + " \"60:I_DAY_NIGHT_FLAG\",\n" + " \"53:PD_UPSELL_PACK_ID\",\n" + " \"146:AON\"\n" + " ]\n" + "}";
final Map<String, Object> response = objectMapper
.readValue(data, objectMapper.getTypeFactory().constructMapType(Map.class, String.class, Object.class));
}
当然,地图中的值类型也可以是对象。在这种情况下,代码可能看起来像这样
public static void main(String[] args) throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
String data = "{\n" + " \"-5\": [\n" + " \"15:D1_CHANNEL_ID_SK\",\n" + " \"23:D1_CALL_BEGIN_DATE\",\n" + " \"87:D1_CELL_ID\"\n" + " ],\n" + " \"-4\": [\n" + " \"31:I_RECHARGE_AMOUNT\",\n" + " \"59:I_INBUNDLED_UNIT\",\n" + " \"60:I_DAY_NIGHT_FLAG\",\n" + " \"53:PD_UPSELL_PACK_ID\",\n" + " \"146:AON\"\n" + " ]\n" + "}";
final Map<String, Your Class Name> response = objectMapper
.readValue(data, objectMapper.getTypeFactory().constructMapType(Map.class, String.class, <Your Class Name>.class));
}
还可以将值类型转换为另一种基于容器的类型(如List),我将其留给您进行探索。