如何使用对象内部对象访问json

时间:2017-01-25 08:56:49

标签: android json

Json Document

我有上面的json文档。如何访问其中的Product1和Product2。 它就像

{
  "abc": "abc",
  "xyz": "xyz",
  "proudct1": {
    "id": "id",
    "name": "name"
  },
  "proudct2": {
    "id": "id",
    "name": "name"
  }
}

2 个答案:

答案 0 :(得分:1)

如果您有多种产品。你的json无效。产品必须是json数组,如

{
  "product": "Product Data",
  "version": 1.1,
  "releaseDate": "2017-01-18T00:00:00.000Z",
  "demo": true,
  "products": [
    {
      "Id": "1",
      "isDisplayed": "Yes",
      "Title1": "Microsoft",
      "Title2": "India",
      "URL": "abc",
      "ImageName": "Microsoft Logo",
      "isImgDownloaded": "Yes",
      "ImageURL": "xyz"
    },
    {
      "Id": "2",
      "isDisplayed": "Yes",
      "Title1": "Google",
      "Title2": "India",
      "URL": "abc",
      "ImageName": "Google Logo",
      "isImgDownloaded": "Yes",
      "ImageURL": "xyz"
    }
  ]
}

你可以像这样访问jsonarray对象

JSONArray result = jsonString.getJSONArray("products");
for (int i = 0; i < result.length(); i++){
    JSONObject jsonObjectItem = result.getJSONObject(i);
    .
    .
    .
}

答案 1 :(得分:0)

您可以使用JSONOBject,它与SDK捆绑在一起,因此无需导入任何第三方库。

假设上面的字符串是response

JSONObject responseObj=new JSONObject(response);
JSONObject product1=responseObj.getJSONObject("product1");
String id=product1.getString("Id");
// ... and similarly for other keys