API always returns JSONObject or JSONArray Best practices

Posted by Michael Laffargue on Programmers See other posts from Programmers or by Michael Laffargue
Published on 2014-08-20T14:36:32Z Indexed on 2014/08/20 16:34 UTC
Read the original article Hit count: 233

Filed under:
|
|

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?

© Programmers or respective owner

Related posts about java

Related posts about api