![](/img/trans.png)
[英]Using streams to apply different functions on key value pair depending on keys
[英]Extracting a key/value pair from json using streams
我的 json 文件是這樣的
{
"Parent1": {
"Child1":"TRUE",
"RandomKey":"TEST-111"
},
"Parent2": {
"Child1":"TRUE",
"AnotherRandomKey":"TEST-432"
}
}
我的目標是根據存在的情況從 Parent1 或 Parent2 中提取 Child1 的第一次出現,如果兩者都存在,它應該只是第一次出現。
我有以下用 java 編寫的代碼,但它總是返回 false。 不知道我做錯了什么
final var content = Jackson.getObjectMapper().readTree(//json link);
Stream.concat(
Optional.ofNullable(content.at("/Parent1/Child1")).stream(),
Optional.ofNullable(content.at("/Parent2/Child1")).stream())
.map(JsonNode::asBoolean)
.filter(Objects::nonNull)
.findFirst()
.orElse(false);
我試圖結合兩個流,只找到 Child1 的第一次出現並返回 boolean。
問題是由於某種原因, JsonNode.asBoolean()
被實現為區分大小寫。 因此,將"TRUE"
解析為false
。
將嘗試將此節點的值轉換為 Java boolean 的方法。 JSON 布爾值 map 自然; integer
0
以外的數字 map 為真,0
映射為false
,Strings
"true"
和"false"
map 對應的值。
這不是很直觀,因為標准 JDK 包裝器類型Boolean
以不區分大小寫的方式執行解析。
作為一種解決方法,我們可以從節點中提取String
,然后應用Boolean.parseBoolean
。
注意:無需創建Optional
即可生成 stream。 在這種情況下, Optional.ofNullable(content.at())
是對可選的濫用(有關可選用法的更多詳細信息, 請參閱)。
為此,我們可以使用Stream.of()
。
public static void main(String[] args) throws JsonProcessingException {
String message = """
{
"Parent1": {
"Child1":"TRUE",
"RandomKey":"TEST-111"
},
"Parent2": {
"Child1":"TRUE",
"AnotherRandomKey":"TEST-432"
}
}""";
ObjectMapper mapper = new ObjectMapper();
JsonNode content = mapper.readTree(message);
boolean result = Stream.of(content.at("/Parent1/Child1"), content.at("/Parent2/Child1"))
.filter(Objects::nonNull)
.map(JsonNode::asText)
.map(Boolean::parseBoolean)
.filter(value -> value) // guarding against the case when node "Parent1" doesn't exist
.findFirst()
.orElse(false);
System.out.println(result);
}
Output:
true
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.