使用不同的密钥解析Json嵌套数组

时间:2017-11-29 07:46:31

标签: android json nested

通常,对于嵌套的JSON数据,如果它们具有相同的密钥,我们可以轻松地解析它。但是如果嵌套JSON中的键不同并且键的名称依赖于另一个嵌套的JSON文件,我们如何解析它?任何人都可以帮忙。

这种JSON数据

{
    "contacts": [
        {
            "id": "c200",
            "name": "Ravi Tamada",
            "phone": {
                "mobile": "+91 0000000000",
                "home": "00 000000",
                "office": "00 000000"
            }
        },
        {
            "id": "c201",
            "name": "Johnny Depp",
            "phone": {
                "mobile": "+91 0000000000",
                "home": "00 000000",
                "office": "00 000000"
            }
        },
        {
            "id": "c202",
            "name": "Leonardo Dicaprio",
            "phone": {
                "mobile": "+91 0000000000",
                "home": "00 000000",
                "office": "00 000000"
            }
        }
    ]
}

我们可以这样解析

for (int i = 0; i < contacts.length(); i++) {
    JSONObject c = contacts.getJSONObject(i);
    String id = c.getString("id");
    String name = c.getString("name");


    // Phone node is JSON Object
    JSONObject phone = c.getJSONObject("phone");
    String mobile = phone.getString("mobile");
    String home = phone.getString("home");
    String office = phone.getString("office");

    // tmp hash map for single contact
    HashMap<String, String> contact = new HashMap<>();

    // adding each child node to HashMap key => value
    contact.put("id", id);
    contact.put("name", name);
    contact.put("email", email);
    contact.put("mobile", mobile);

    // adding contact to contact list
    contactList.add(contact);
}

但是,如果嵌套的JSON值具有不同的键,我们如何解析?我的JSON数据如下:

{ "kind": "webfonts#webfontList",
"items": [
  {
   "variants": [
    "regular",
    "italic"
   ],

   "files": {
    "regular": 
"http://fonts.gstatic.com/s/abeezee/v11/mE5BOuZKGln_Ex0uYKpIaw.ttf",
    "italic": 
"http://fonts.gstatic.com/s/abeezee/v11/kpplLynmYgP0YtlJA3atRw.ttf"
   }
  },
  {

   "variants": [
    "regular"
   ],

   "files": {
    "regular": 
"http://fonts.gstatic.com/s/abel/v8/RpUKfqNxoyNe_ka23bzQ2A.ttf"
   }
  },
  {

   "variants": [
    "regular",
    "500",
    "600",
    "700",
    "800"
   ],
   "files": {
    "regular":     "http://fonts.gstatic.com/s/abhayalibre/v3/zTLc5Jxv6yvb1nHyqBasVy3USBnSvpkopQaUR-2r7iU.ttf",
    "500":     "http://fonts.gstatic.com/s/abhayalibre/v3/wBjdF6T34NCo7wQYXgzrc5MQuUSAwdHsY8ov_6tk1oA.ttf",
    "600":     "http://fonts.gstatic.com/s/abhayalibre/v3/wBjdF6T34NCo7wQYXgzrc2v8CylhIUtwUiYO7Z2wXbE.ttf",
    "700":     "http://fonts.gstatic.com/s/abhayalibre/v3/wBjdF6T34NCo7wQYXgzrc0D2ttfZwueP-QU272T9-k4.ttf",
    "800":     "http://fonts.gstatic.com/s/abhayalibre/v3/wBjdF6T34NCo7wQYXgzrc_qsay_1ZmRGmC8pVRdIfAg.ttf"
   }
  }
]
}
有人,请帮忙......

0 个答案:

没有答案