How to check whether the given object is object or Array in JSON string

后端 未结 4 1781
不思量自难忘°
不思量自难忘° 2020-12-05 08:04

I am getting JSON string from website. I have data which looks like this (JSON Array)

 myconf= {URL:[blah,blah]}

but some times this data c

4条回答
  •  误落风尘
    2020-12-05 08:37

    Using @Chao answer i can solve my problem. Other way also we can check this.

    This is my Json response

    {
      "message": "Club Details.",
      "data": {
        "main": [
          {
            "id": "47",
            "name": "Pizza",
    
          }
        ],
    
        "description": "description not found",
        "open_timings": "timings not found",
        "services": [
          {
            "id": "1",
            "name": "Free Parking",
            "icon": "http:\/\/hoppyclub.com\/uploads\/services\/ic_free_parking.png"
          } 
        ]
      }
    }
    

    Now you can check like this that which object is JSONObject or JSONArray in response.

    String response = "above is my reponse";
    
        if (response != null && constant.isJSONValid(response))
        {
            JSONObject jsonObject = new JSONObject(response);
    
            JSONObject dataJson = jsonObject.getJSONObject("data");
    
            Object description = dataJson.get("description");
    
            if (description instanceof String)
            {
                Log.e(TAG, "Description is JSONObject...........");
            }
            else
            {
                Log.e(TAG, "Description is JSONArray...........");
            }
        }
    

    This is used for check that received json is valid or not

    public boolean isJSONValid(String test) {
            try {
                new JSONObject(test);
            } catch (JSONException ex) {
                // e.g. in case JSONArray is valid as well...
                try {
                    new JSONArray(test);
                } catch (JSONException ex1) {
                    return false;
                }
            }
            return true;
        }
    

提交回复
热议问题