从 JSON 响应中获取空值



我已经使用放心从API中提取了JSON响应,它看起来像这样:

[
{
"firstKey": ["value1", "value2"],
"secondKey": 4,
"thirdValue": "value3",
"fourthValue":"value4"
},
{
"firstKey": ["value5", "value6"],
"secondKey": 5,
"thirdValue": "value7",
"fourthValue":"value8"
}
]

现在,我的实际 JSON 响应将在 JSON 数组中包含数千个 JSON 对象,并且某些键将具有空值,例如。"secondKey"在某些JSON对象中具有空值。 我需要获取 JSON 响应中具有空值的所有键。关于我该怎么做的任何想法?

我解决这个问题的想法是使用 Jackson 库反序列化 JSON 并获取所有空值。但是,有没有考虑性能的有效解决方案?

假设你使用的是JavaScript,你的空值看起来像这样"secondKey": null;

以下是获取这些密钥的一种方法:

var arr = JSON.parse(json_array); // json_array is your json response
var nullKeys = [];
for (var i = 0; i < arr.length; i++){
var obj = arr[i];
for (var key in obj)
if(obj[key] == null) 
nullKeys.push(key);
}

使用带有组匹配器的正则表达式模式来提取具有null值的键。

String pattern = ""(.*)": null";
String json = "[n" +
"{n" +
""firstKey": ["value1", "value2"],n" +
""secondKey": null,n" +
""thirdValue": null,n" +
""fourthValue":"value4"n" +
"},n" +
"{n" +
""firstKey": ["value5", "value6"],n" +
""secondKey": null,n" +
""thirdValue": "value7",n" +
""fourthValue":"value8"n" +
"}n" +
"]";
Matcher matcher = Pattern.compile(pattern).matcher(json);
while (matcher.find()) {
System.out.println(matcher.group(1));
}

以下是输出

secondKey
thirdValue
secondKey

你部分回答了自己 - 最有效的方法之一实际上是使用杰克逊图书馆。在这种情况下,可以使用其流式处理 API 来有效地分析输入 JSON 字符串。

下面是如何输出所有键将空值的示例,无论它们位于 JSON 结构中的哪个位置:

JsonParser parser = new JsonFactory().createParser(json);
while (parser.nextToken() != null) {
if (parser.currentToken() == JsonToken.VALUE_NULL) {
System.out.println("Got null in key: " + parser.currentName());
}
}

请注意,如果数组中有null,这也将输出Got null in key: null。这是一个稍微复杂的代码,它试图解决这个问题:

JsonParser parser = new JsonFactory().createParser(content);
Stack<String> nestedArrays = new Stack<String>();
while (parser.nextToken() != null) {
// note: a switch could be used as well
if (parser.currentToken() == JsonToken.START_ARRAY) {
// note: a top level array returns `null` here
nestedArrays.push(parser.currentName());
}
if (parser.currentToken() == JsonToken.END_ARRAY) {
nestedArrays.pop();
}
if (parser.currentToken() == JsonToken.VALUE_NULL) {
String key = parser.currentName();
if (key == null) {
key = nestedArrays.lastElement();
}
System.out.println("Got null in key / array: " + key);
}
}

最新更新