简体   繁体   English

Jackson JsonNode 和 Java Streams 返回 Optional Empty

[英]Jackson JsonNode and Java Streams to return Optional Empty

So I have a json input, something like this:所以我有一个 json 输入,如下所示:

{
    "a":"something",
    "b":"something2"
}

This input can come in 2 other forms:此输入可以有两种其他形式:

{
    "a":"something",
    "b":""
}

And并且

{
    "a":"something"
}

I have a input class like this that I store it in:我有一个这样的输入类,我将它存储在:

public class Foo {
    private String a;
    private Optional<String> b;
}

In the latter 2 cases I want to store b as Optional.empty().在后两种情况下,我想将 b 存储为 Optional.empty()。 I have figured out how to do that in the 3rd case with this line of code:我已经想出了如何使用这行代码在第 3 种情况下做到这一点:

Optional.ofNullable(inputNode.get("b")).map(node -> node.asText())

This works well for the 3rd case.这适用于第 3 种情况。 It returns Optional.empty.它返回 Optional.empty。 But not so much for the 2nd case because b ends up just being an empty string.但对于第二种情况并没有那么多,因为b最终只是一个空字符串。 I tried to use .reduce before and after the .map but for some reason it won't let me use that anywhere.我试图在.map之前和之后使用.reduce但由于某种原因它不会让我在任何地方使用它。

And idea how to achieve what I want?以及如何实现我想要的想法?

You can filter the Optional to check that the value is not the empty String:您可以过滤 Optional 以检查该值是否为空字符串:

Optional<String> b = Optional.ofNullable(inputNode.get("b"))
        .map(JsonNode::asText)
        .filter(s -> !s.isEmpty());

此代码还有助于:

Optional.ofNullable(jsonNode.findValue("XYZ")).map(JsonNode::asText).orElse(null);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM