Kali Aney Kali Aney - 4 months ago 10
Android Question

Android volley : how to check json type before parsing it

Is it possible to check the type of json beforehand? I'm somteimes getting an array and sometimes an object and I don't see how to handle these 2 cases without doing 2 different functions...

public void RequestApi( String url, final ApiResponse<ApiResult> completion )
{
Log.v("Performing request: ", url);
JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.GET, hostname+url, (JSONObject) null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response)
{
Log.v("RequestApi Response", response.toString());
//Log.v("Data: ", response.toString());
try {
ApiResult res = new ApiResult();
Boolean success = response.getBoolean("success");

//here need to check type, sometimes array, sometimes object
JSONArray data = response.getJSONArray("data");

res.success = success;
res.data = data;
completion.onCompletion(res);

} catch (JSONException e) {
e.printStackTrace();
}

}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
ApiResult res = new ApiResult();
res.success = false;
completion.onCompletion(res);
}
}
);

AppController.getInstance().addToRequestQueue(jsonRequest);
}

Answer

Most simple solution - look at first string character. If it is { - object, if [ - array. But I think better to do following:

try {
    JSONObject object = new JSONObject(value);
}
catch (JSONException) {
    //if it throws, "value" contains not a JSONObject
    JSONArray array = new JSONArray(value);
}
Comments