我有个json:
{
"text":[
{"a":1},
{"b":2}
]
}我有这样的代码:
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();我怎么能做到这一点,而不把它映射到对象呢?
或者做一些类似于JsonNode[] array和array[0]代表a和array[1]代表b的事情。
发布于 2020-05-29 16:36:40
如果您想显式遍历json并找到a的值,您可以为您指定的json这样做。
String aValue = jsonNode.get("text").get(0).get("a").asText();找到b的值将是
String bValue = jsonNode.get("text").get(1).get("b").asText();您还可以遍历文本数组中的元素,并将a和b的值作为
for (JsonNode node : jsonNode.get("text")) {
System.out.println(node.fields().next().getValue().asText());
}这将在控制台上打印下面的内容
1
2https://stackoverflow.com/questions/62090484
复制相似问题