API always returns JSONObject or JSONArray Best practices
- by Michael Laffargue
I'm making an API that will return data in JSON.
I also wanted on client side to make an utility class to call this API.
Something like :
JSONObject sendGetRequest(Url url);
JSONObject sendPostRequest(Url url, HashMap postData);
However sometimes the API send back array of object [{id:1},{id:2}]
I now got two choices ():
Make the method test for JSONArray or JSONObject and send back an Object that I will have to cast in the caller
Make a method that returns JSONObject and one for JSONArray (like sendGetRequestAndReturnAsJSONArray)
Make the server always send Arrays even for one element
Make the server always send Objects wrapping my Array
I going for the two last methods since I think it would be a good thing to force the API to send consistent type of data.
But what would be the best practice (if one exist).
Always send arrays? or always send objects?