【问题标题】:How to iterate over json Array having multiple json objects with different header如何迭代具有多个具有不同标头的json对象的json数组
【发布时间】:2017-04-25 16:03:39
【问题描述】:

我从 rest webservice 得到一个 json 数组作为响应,就像

 [{
"mutualFund":{"fundCode":"XYZ","fundName": "Funds - Global Income 
 Fund (G)-SGD","isin":"LU0882574725","sedol":"1234"}},

 {"brokers":{"fundID":"abcd","fundName":"Funds - Focus 
  Fund A-USD","isin":"LU0197229882","sedol":"6543"}
 }]

我正在尝试遍历所有互惠基金数组属性以获取它们的值。我试过这个代码 sn-p 但它返回错误——“mutualFund 不存在”。在我的 json 文件中,一些对象属于共同基金类型,而一些对象属于具有不同属性的其他类型,因此我必须迭代并区分它们。所以我不能使用 getJSONObject(i)。

 JSONArray jsonArray=new JSONArray(response.getBody());
  for(int i=0;i<jsonArray.length();i++){
  JSONObject jsonObject=jsonArray.getJSONObject("mutualFund");
  }

【问题讨论】:

  • 你使用的是哪个 json 库?

标签: java json


【解决方案1】:

根据您使用的类和方法,我假设您使用org.primefaces.json 类。 但即使你使用不同的 API,逻辑也基本相同。

首先,看看你的 JSON 结构:

[
  {
    "mutualFund": {
      "fundCode": "XYZ",
      "fundName": "Funds-GlobalIncomeFund(G)-SGD","isin":"LU0882574725","sedol":"1234"
     }
  },
  {
    "brokers": {
      "fundID": "abcd",
      "fundName": "Funds-FocusFundA-USD","isin":"LU0197229882","sedol":"6543"
    }
  }
]

这是一个包含 2 个元素的数组。第一个元素是一个只有一个键 (mutualFund) 和它的值(另一个具有 fundCodefundName 键的对象)的对象。请注意,对象具有一个mutualFund 键,并且您试图获取它,就好像对象本身一个mutualFund。这就是导致错误的原因。

因此,要获取所有mutualFund 对象,您需要检查数组中的每个元素,并且对于每个元素,您必须检查它是否具有mutualFund 键。那么你的代码会是这样的:

for (int i = 0; i < jsonArray.length(); i++) {
    // get object i
    JSONObject jsonObject = jsonArray.getJSONObject(i);
    // check if object has mutualFund key
    if (jsonObject.has("mutualFund")) {
        // get mutualFund object and do something with it
        JSONObject mutualFund = jsonObject.getJSONObject("mutualFund");
        // do something with mutualFund object (you can get values for fundCode and fundName keys, etc)
    }
}

注意:如果您使用不同的 JSON API,方法名称可能会有所不同(而不是 has,有些使用 containsKeyget(key) != null,但查找的逻辑mutualFund 对象将是相同的)。

【讨论】:

  • 我正在使用 org.json 库。
  • org.json 的代码相同。你测试过吗?
猜你喜欢
  • 2012-06-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-19
  • 2021-05-14
  • 1970-01-01
  • 1970-01-01
  • 2021-03-14
相关资源
最近更新 更多