我不得不处理一些json,它可能以稍微不同的格式出现(而且我只需要json数据的一个子集),我使用JsonPointer (来自杰克逊)来查询json。我为这个问题写了一个非功能性的解决方案,这对我有用,但我想尝试一种功能性的学习方法。在下面的测试程序中,您可以看到我的两个解决方案。它们都能工作,但是功能解决方案变得相当冗长,我收到了Intellij关于在没有isPresent检查的情况下使用get()的恼人警告。我希望看到如何改进功能实现的建议,我很高兴看到使用第三方库的解决方案。这里的基本问题,我想,是如何建模一个if-否则-if-else,其中每个分支应该返回一些值,以一种函数的方式。
@Test
public void testIt() {
ObjectMapper om = new ObjectMapper();
ImmutableList.of(
"{ \"foo\": { \"key\": \"1\" } }",
"{ \"bar\": { \"key\": \"1\" } }",
"{ \"key\": \"1\" }")
.forEach(str -> {
try {
System.out.println("Non-functional: " + getNode(om.readTree(str)));
System.out.println("Functional: " + getNodeFunc(om.readTree(str)));
} catch (Exception e) {
throw new RuntimeException("", e);
}
});
}
private JsonNode getNode(JsonNode parentNode) {
JsonPointer jp1 = JsonPointer.compile("/foo");
JsonPointer jp2 = JsonPointer.compile("/bar");
if (!parentNode.at(jp1).isMissingNode()) {
return parentNode.at(jp1);
} else if (!parentNode.at(jp2).isMissingNode()) {
return parentNode.at(jp2);
}
return parentNode;
}
private JsonNode getNodeFunc(JsonNode parentNode) {
BiFunction<JsonNode, String, Optional<JsonNode>> findNode = (node, path) -> {
JsonPointer jp = JsonPointer.compile(path);
return node.at(jp).isMissingNode() ? Optional.empty() : Optional.of(node.at(jp));
};
return findNode.apply(parentNode, "/foo")
.map(Optional::of)
.orElseGet(() -> findNode.apply(parentNode, "/bar"))
.map(Optional::of)
.orElse(Optional.of(parentNode))
.get(); // Intellij complains here: Optional.get() without isPresent check
}发布于 2019-01-22 20:11:12
我会把它重写
private JsonNode getNodeFunc2(JsonNode parentNode) {
return Stream.of(JsonPointer.compile("/foo"), JsonPointer.compile("/bar"))
.filter(i -> !parentNode.at(i).isMissingNode())
.findFirst()
.map(parentNode::at)
.orElse(parentNode);
}或
private JsonNode getNodeFunc3(JsonNode parentNode) {
return Stream.of(JsonPointer.compile("/foo"), JsonPointer.compile("/bar"))
.map(parentNode::at)
.filter(Predicate.not(JsonNode::isMissingNode))
.findFirst()
.orElse(parentNode);
}或
private JsonNode getNodeFunc4(JsonNode parentNode) {
return Stream.of("/foo", "/bar")
.map(JsonPointer::compile)
.map(parentNode::at)
.filter(Predicate.not(JsonNode::isMissingNode))
.findFirst()
.orElse(parentNode);
}因为那首歌
if (!parentNode.at(jp1).isMissingNode()) {
return parentNode.at(jp1);
} else if (!parentNode.at(jp2).isMissingNode()) {
return parentNode.at(jp2);
}是代码复制,可以由循环灵活地处理:
for (JsonPointer jsonPointer : jsonPointers) {
JsonNode kid = parentNode.at(jsonPointer);
if (!kid.isMissingNode()) {
return kid;
}
}发布于 2019-01-22 21:44:24
需要考虑的是,getNode函数是完美的函数代码:
https://stackoverflow.com/questions/54315439
复制相似问题