-3

Json Document

I have the above json document. How can I access Product1 and Product2 in it. it's like

{
  "abc": "abc",
  "xyz": "xyz",
  "proudct1": {
    "id": "id",
    "name": "name"
  },
  "proudct2": {
    "id": "id",
    "name": "name"
  }
}
Nayan Srivastava
  • 3,655
  • 3
  • 27
  • 49
Abhinav Nigam
  • 21
  • 2
  • 7

2 Answers2

3

if you have multiable products. Your json is not effective.Products must be json array like

{
  "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"
    }
  ]
}

And you can access jsonarray object like this

JSONArray result = jsonString.getJSONArray("products");
for (int i = 0; i < result.length(); i++){
    JSONObject jsonObjectItem = result.getJSONObject(i);
    .
    .
    .
}
Muhammed GÜNEŞ
  • 304
  • 2
  • 15
  • voting up as it also suggest efficient structure :) – Nayan Srivastava Jan 25 '17 at 09:28
  • I have updated my json and trying to access it through assets folder but the following error occurs while building C:\Users\Abhinav\AndroidStudioProjects\Internship\app\src\main\res\assets\demo.json Error:(1, 1) Error: Content is not allowed in prolog. Error:Execution failed for task ':app:mergeDebugResources'. > C:\Users\Abhinav\AndroidStudioProjects\Internship\app\src\main\res\assets\demo.json:1:1: Error: Content is not allowed in prolog. – Abhinav Nigam Jan 25 '17 at 13:25
  • Did you check this [answer](http://stackoverflow.com/a/19945484/1929448) – Muhammed GÜNEŞ Jan 25 '17 at 13:31
0

You can use JSONOBject, it comes bundled with SDK so no need to import any third party lib.

Assume the above string is response.

JSONObject responseObj=new JSONObject(response);
JSONObject product1=responseObj.getJSONObject("product1");
String id=product1.getString("Id");
// ... and similarly for other keys
Nayan Srivastava
  • 3,655
  • 3
  • 27
  • 49