gpt4 book ai didi

java - 使用 Jackson 解析 JSON 时获取特定值

转载 作者:搜寻专家 更新时间:2023-10-31 19:27:30 26 4
gpt4 key购买 nike

我有以下 JSON:

[  
{
"A":"Lorem Ipsum ",
"B":"Lorem Ipsum ",
"C":"Lorem Ipsum ",
"D":"Lorem Ipsum ",
"E":"Lorem Ipsum ",
"F":"Lorem Ipsum ",
"G":301,
"H":[
{
"Lorem Ipsum ":4,
"Lorem Ipsum ":20,
"Lorem Ipsum":0
},
{
"Lorem Ipsum ":5,
"Lorem Ipsum ":19.2,
"Lorem Ipsum ":0.8
},
{
"Lorem Ipsum ":1,
"Lorem Ipsum ":8,
"Lorem Ipsum ":4
},
{
"Lorem Ipsum ":3,
"Lorem Ipsum ":14.2,
"Lorem Ipsum ":5.8
},
{
"Lorem Ipsum ":2,
"Lorem Ipsum ":20,
"Lorem Ipsum ":0
}
],
"I":[

],
"J":[

],
"20-01-2014":20,
"27-01-2014":19.2,
"30-12-2013":8,
"13-01-2014":14.2,
"06-01-2014":20,
"K":"81.40"
},
{
"reportKey":"something"
}
]

我想获取 reportKey 值,然后将其从文件中删除。但首先我需要访问它,但我的代码似乎不起作用:

final ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readValue(rawContentParameters, JsonNode.class);

logger.info("ExportController : generatesExportExcel : parameters: {}", jsonNode.get("reportKey").textValue());

但我得到了一个 java.lang.NullPointerException。为什么?

解决方案:

final ObjectMapper objectMapper = new ObjectMapper();
JsonNode rootNode = objectMapper.readValue(rawContentParameters, JsonNode.class);

logger.info("ExportController : generatesExportExcel : parameters: {}", rootNode.get(rootNode.size() - 1).get("reportKey").textValue());

最佳答案

您正在访问根 JsonNode,就像它是一个对象一样,但它被包装在一个数组中。在访问 reportKey 之前,您需要从数组中提取第二个对象:

JsonNode array = objectMapper.readValue(rawContentParameters, JsonNode.class);
JsonNode object = array.get(1);
String reportKey = object.get("reportKey").textValue();
logger.info("ExportController : generatesExportExcel : parameters: {}", reportKey);

关于java - 使用 Jackson 解析 JSON 时获取特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30800182/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com