簡體   English   中英

用Java解析JSON數組

[英]Parsing JSON array in Java

我目前正在將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 這是一個示例(未經測試)。 它將允許您檢查是否存在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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM