[英]Get element from JsonNode array
I have this json:我有这个 json:
{
"text":[
{"a":1},
{"b":2}
]
}
I have this code:我有这个代码:
JsonNode jsonNode = (new ObjectMapper()).readTree(jsonString);
//get first element from "text"
//this is just an explanation of what i want
String aValue = jsonNode.get("text")[0]
.get("a")
.asText();
How I can done that, without mapping it to an object?如果不将其映射到 object,我该如何做到这一点?
Or do something like JsonNode[] array
and array[0]
represent a
and array[1]
represent b
或者做类似JsonNode[] array
和array[0]
代表a
和array[1]
代表b
If you want to explicitly traverse through the json and find the value of a
, you can do it like this for the json that you specified.如果您想显式遍历 json 并找到a
的值,您可以对您指定的 json 执行此操作。
String aValue = jsonNode.get("text").get(0).get("a").asText();
Finding the value of b
would be找到b
的值将是
String bValue = jsonNode.get("text").get(1).get("b").asText();
You can also traverse through the elements within the text array and get the values of a
and b
as您还可以遍历文本数组中的元素并获取a
和b
的值作为
for (JsonNode node : jsonNode.get("text")) {
System.out.println(node.fields().next().getValue().asText());
}
And that would print the below on the console这将在控制台上打印以下内容
1
2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.