![](/img/trans.png)
[英]How to create pojo class using json data/json response in java?
[英]How to iterate a big Json in Java that can have multiple level of Objects and Arrays without using a pojo class?
How to iterate a big Json in Java that can have multiple levels of Objects and Arrays without using a pojo class for parsing? 对象和数组键名未知。 是否有任何通用代码可以做到这一点? 在此示例 json 中,必须打印 value 键中的所有数据。 样品 Json:
"X": [
{
"Y": {
"value": "Test"
},
"Z": {
"value": 2
}
}
]
真正的 json 可以非常大,具有多个 Array 和 object 级别。
注意:请不要将此标记为重复,因为其他问题与确切要求无关。
使用 Jackson,您可以读取\加载JSON
,如下所示:
private JsonNode loadJson(String json) throws IOException {
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readTree(json);
return rootNode;
}
样品JSON
:
{
"name":{
"first":"Tatu",
"last":"Saloranta"
},
"title":"Jackson founder",
"company":"FasterXML",
"pets":[
{
"type":"dog",
"number":1
},
{
"type":"fish",
"number":50
}
]
}
要解析JSON
:
String json = "{\"name\": {\"first\":\"Tatu\",\"last\":\"Saloranta\"},\"title\":\"Jackson founder\",\"company\":\"FasterXML\",\"pets\":[{\"type\":\"dog\",\"number\":1},{\"type\":\"fish\",\"number\":50}]}";
JsonNode rootNode = loadJson(json);
JsonNode nameNode = rootNode.get("name");
String firstName = nameNode.get("first").asText();
String lastName = nameNode.get("last").asText();
String title = rootNode.get("title").asText();
String company = rootNode.get("company").asText();
JsonNode petsArrayNode = rootNode.get("pets");
for (final JsonNode petNode : petsArrayNode ) {
String type = petNode.get("type").asText();
int number = petNode.get("number").asInt();
}
您可以在此处阅读更多信息: https://www.baeldung.com/jackson-json-node-tree-model
您可以使用 JSR 374 中的 JsonParser 将 JSON 读取为 stream(JSON 处理 API aka JSON-P):
import java.io.*;
import javax.json.Json;
import javax.json.stream.JsonParser;
import javax.json.stream.JsonParser.Event;
public static class ParserTest {
public static void main(String[] args) {
String jsonString = "{\"X\": [\n" +
" {\n" +
" \"Y\": {\n" +
" \"value\": \"Test\"\n" +
" },\n" +
" \"Z\": {\n" +
" \"value\": 2\n" +
" }\n" +
"}\n" +
"]}";
JsonParser parser = Json.createParser(new StringReader(jsonString));
String key = null;
while (parser.hasNext()) {
Event event = parser.next();
switch (event) {
case KEY_NAME:
key = parser.getString();
break;
case VALUE_STRING:
case VALUE_NUMBER:
case VALUE_TRUE:
case VALUE_FALSE:
case VALUE_NULL:
System.out.println(key + ": " + parser.getString());
break;
}
}
}
}
您需要包括 glassfish 实现
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.json</artifactId>
<version>1.1.4</version>
</dependency>
代码示例取自https://www.tutorialspoint.com/how-to-parse-a-json-string-using-streaming-api-in-java
您可以在此处阅读有关 JSON-P 的更多信息: https://javaee.github.io/jsonp/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.