java 使用 Jackson 的 JsonNode.findPath(String fieldName) 获取具有非唯一列名的字段的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37979156/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using Hymanson's JsonNode.findPath(String fieldName) to get the value of a field with a Non-Unique column name
提问by daniel9x
Consider the following (simplied) JSON tree structure:
考虑以下(简化的)JSON 树结构:
{
"id": "1",
"metaData": {
"name": "nestedName"
},
"name": "rootName"
}
I put this stucture in a com.fasterxml.Hymanson.databind.JsonNode object. To get the String values of these columns, I need only include this statement in my Java code:
我将此结构放在 com.fasterxml.Hymanson.databind.JsonNode 对象中。要获取这些列的字符串值,我只需要在我的 Java 代码中包含此语句:
String id = jsonNode.findPath("id").textValue();
I love this not only for its simplicity, but that my code doesn't have to be aware of the JSON tree structure it's parsing. I realize that if I want [root][name] specifically though, I'll have to have some kind of determination logic.
我喜欢这不仅是因为它的简单性,而且我的代码不必知道它正在解析的 JSON 树结构。我意识到如果我特别想要 [root][name],我必须有某种确定逻辑。
My question is, what is the least amount of logic I will require in order to somehow distinguish/specify what "name" to get? I've looked into the JsonNode.findValues(String fieldName) to get a list of the values, but still not sure how I would then determine which value was coming from which "name" and how to choose the "root" one, or at least, the one closest to the root.
我的问题是,为了以某种方式区分/指定要获得的“名称”,我需要的最少逻辑是多少?我查看了 JsonNode.findValues(String fieldName) 以获取值列表,但仍然不确定我将如何确定哪个值来自哪个“名称”以及如何选择“根”一个,或者至少,最接近根的那个。
Apologies if this is a duplicate question but I couldn't find an exact match, so asking again.
如果这是一个重复的问题,但我找不到完全匹配的问题,请再次提问。
回答by qHack
If you want a node directly underneath the root use .get()
如果你想要一个直接在根下面的节点,请使用 .get()
jsonNode.get("id").textValue();
If you want to get "name" but you have problems with ambiguity you can do something like
如果你想得到“名字”但你有歧义的问题,你可以做类似的事情
jsonNode.findPath("metaData").findPath("name").textValue();
But then of course you know have to know something about the schema.
但是当然,您必须了解有关架构的知识。