gpt4 book ai didi

java - 在Java中解析JSON数组

转载 作者:行者123 更新时间:2023-12-02 04:05:18 24 4
gpt4 key购买 nike

我目前正在将 JSON 文件解析为我的 Java 程序,但遇到了问题。我得到一个 JSON 数组,如下所示:

[
{
"itemType": "magazineArticle",
"creators": [
{
"firstName": "J. Antonio",
"lastName": "Garcia-Macias",
"creatorType": "author"
},
{
"firstName": "Jorge",
"lastName": "Alvarez-Lozano",
"creatorType": "author"
},
{
"firstName": "Paul",
"lastName": "Estrada-Martinez",
"creatorType": "author"
},
{
"firstName": "Edgardo",
"lastName": "Aviles-Lopez",
"creatorType": "author"
}
],
"notes": [],
"tags": [],
"title": "Browsing the Internet of Things with Sentient Visors",
"publicationTitle": "Computer",
"volume": "44",
"issue": "5",
"ISSN": "0018-9162",
"date": "2011",
"pages": "46-52",
"abstractNote": "Unlike the traditional Internet, the emerging Internet of Things constitutes a mix of virtual and physical entities. A proposed IoT browser enables the exploration of augmented spaces by identifying smart objects, discovering any services they might provide, and interacting with them.",
"extra": "CICESE Research Center, Mexico; CICESE Research Center, Mexico; CICESE Research Center, Mexico; CICESE Research Center, Mexico",
"libraryCatalog": "IEEE Computer Society"
}
]

问题是我每次解析时都必须检查数组中是否包含名为“extra”的字段,因为每次解析时都不包含它。那么我该如何检查“extra”字段是否存在?

最佳答案

没有框架,您可以使用 org.json.* 中的 JSONObjectJSONArray。这是一个示例(未测试)。它将允许您检查额外键是否存在

String jsonAsString = "/*Your json as a String*/";
JsonArray jsonArray = new JSONArray(jsonAsString);

for(int i=0; i<jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
//Get values from your jsonObject
jsonObject.has("extra"); //Check if extra is present
}

关于java - 在Java中解析JSON数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34352213/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com