[英]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.