Zeeshan
Zeeshan

Reputation: 751

Nested JSON Objects length

I have following JSON String.

{
  "data": [
    {
      "city_id": "1",
      "city_name_eng": "Multan",
      "0": {
        "category_id": "1",
        "city_id": "1",
        "category_name_eng": "Mango",
        "0": {
          "product_id": "1",
          "category_id": "1",
          "product_name_eng": "Mango1"
        },
        "1": {
          "product_id": "2",
          "category_id": "1",
          "product_name_eng": "Mango2"
        },
        "2": {
          "product_id": "3",
          "category_id": "1",
          "product_name_eng": "Mango3"
        },
        "3": {
          "product_id": "4",
          "category_id": "1",
          "product_name_eng": "Mango1"
        }
      },
      "1": {
        "category_id": "2",
        "city_id": "1",
        "category_name_eng": "Shoes"
      },
      "2": {
        "category_id": "3",
        "city_id": "1",
        "category_name_eng": "Bank"
      }
    },
    {
      "city_id": "2",
      "city_name_eng": "Lahore",
      "3": {
        "category_id": "4",
        "city_id": "2",
        "category_name_eng": "Food"
      },
      "4": {
        "category_id": "5",
        "city_id": "2",
        "category_name_eng": "Computer"
      },
      "5": {
        "category_id": "6",
        "city_id": "2",
        "category_name_eng": "Mobile"
      }
    }
  ]
}

I want to have length of JSONObject. Basically, the first object having "city_id": "1" has 4 nested JSONObjects and 2 values, i.e. city_id and city_name_eng. When i use objJSON.length() , it gives me length of 6. But on the contrary I want to have 4 nested JSONObjects, how can i get it on run-time? (whether the nested jsonobjects are 3 or 4 or any number)

How to differentiate between nested JSONObjects and key values?

Upvotes: 1

Views: 632

Answers (1)

Vinay S Shenoy
Vinay S Shenoy

Reputation: 4028

If the website is your own, then I suggest reworking the code to return JSONArrays where appropriate.

Otherwise, jsonObj.keys() will return an Iterator which you an use to iterate over the keys and parse out your objects.

Upvotes: 1

Related Questions