【问题标题】:Parsing JSON array in Java在 Java 中解析 JSON 数组
【发布时间】:2015-12-18 09:23:03
【问题描述】:

我目前正在将一个 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”字段是否存在呢?

【问题讨论】:

  • 不能用JSON解析框架吗?一定要自己动手吗?
  • 我必须手工完成。
  • 你可以使用 Jackson 或 JsonSimple 吗?
  • 向我们展示您的解析代码
  • 如果我实际上可以在我的java程序中做一个简单的检查,我会更喜欢。就像我在程序中获得抽象字段时一样: String abstracts = obj.getString("abstractNote");我想做的只是在我尝试获取该字段时进行检查,如果该字段确实存在。

标签: java arrays json parsing


【解决方案1】:

没有框架,你可以使用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
}

【讨论】:

    【解决方案2】:

    像这样使用 JSONObject 的“has”方法:

    Array.getJSONObject(j).has("extra")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-02
      • 1970-01-01
      • 1970-01-01
      • 2014-03-17
      相关资源
      最近更新 更多