[英]Parsing JSON array in Java
I'm currently parsing a JSON file to my Java Program and I ecounter a problem. 我目前正在将JSON文件解析到Java程序中,遇到了问题。 I get a JSON array that can look like this for example: 我得到一个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"
}
]
The problem is I have to do a check each time I parse if the field called "extra" is in the array, since it's not included every time i parse. 问题是我每次解析时都必须检查一下是否名为“ extra”的字段在数组中,因为每次解析时都不会包含该字段。 So how do I do that check to see if the field "extra" exists? 因此,我该如何检查字段“ extra”是否存在?
Without framework, you can use JSONObject
and JSONArray
from org.json.*
. 如果没有框架,则可以使用org.json.*
JSONObject
和JSONArray
。 Here is an example (not tested). 这是一个示例(未经测试)。 It will allows you to check if the extra
key is present 它将允许您检查是否存在extra
密钥
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
}
像这样使用JSONObject的“ has”方法:
Array.getJSONObject(j).has("extra")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.