Sai's Stack
Sai's Stack

Reputation: 1385

How to send Array of Objects in retrofit Android?

I have an below array of objects to be passed in the service call.

    [
  {
    "ParkingSpace": {
        "sid": "WorldSensing.vhu6lom3sovk6ahpogebfewk5kqadvs4.5385fc250cf2497dfe5679d1"
    }
}, 
  {
    "ParkingSpace": {
        "sid": "WorldSensing.vhu6lom3sovk6ahpogebfewk5kqadvs4.5385ff2f0cf2497dfe567c0c"
    }
}, 
  {
    "ParkingSpace": {
        "sid": "WorldSensing.vhu6lom3sovk6ahpogebfewk5kqadvs4.5385fd700cf2e65ecf6330c6"
    }
}, {
    "ParkingSpace": {
        "sid": "WorldSensing.vhu6lom3sovk6ahpogebfewk5kqadvs4.5385fefe0cf2497dfe567bee"
    }
}, {
    "ParkingSpace": {
        "sid": "WorldSensing.vhu6lom3sovk6ahpogebfewk5kqadvs4.5385ff690cf2497dfe567c3f"
    }
}, {
    "ParkingSpace": {
        "sid": "WorldSensing.vhu6lom3sovk6ahpogebfewk5kqadvs4.55e972d21170d0c2fd7d15b1"
    }
}]

I am trying like below:

private String generateParkingspaceBody(final List<String> listOfsIds) {

        //sids array
        JSONArray sidsArray = new JSONArray();

        for (String sId: listOfsIds) {

            //creating sidObject and object
            JSONObject sIdObject = new JSONObject();
            JSONObject object = new JSONObject();


            try {
                sIdObject.put("sid", sId);
                object.put("ParkingSpace",sIdObject);
                sidsArray.put(object);
            } catch (JSONException e) {
                CPALog.e(TAG,e.getMessage());
            }



        }
        return sidsArray.toString();
    }

Sending this string into the service call like:

 Response getNearByParkingSpaces(@Header("Authorization") String accessToken,
                                    @Header("Content-Type") String contentType,
                                    @Body String arrayOfSids);

But in request showing in the logact is :

"[{\"ParkingSpace\":{}},{\"ParkingSpace\":{}},{\"ParkingSpace\":{}},{\"ParkingSpace\":{}},{\"ParkingSpace\":{}},{\"ParkingSpace\":{}},{\"ParkingSpace\":{}},{\"ParkingSpace\":{}},{\"ParkingSpace\":{}},{\"ParkingSpace\":{}},{\"ParkingSpace\":{}},{\"ParkingSpace\":{}},{\"ParkingSpace\":{}}]"

Please help me, how to send this request?

Thanks in advance.

Upvotes: 5

Views: 14622

Answers (3)

Rakesh Jha
Rakesh Jha

Reputation: 379

If you want to upload array of object using Retrofit then follow the steps. It will work 100%. In my case I have 2 params one is userid and second is location_data. In second params I have to pass array of objects.

@FormUrlEncoded
@POST("api/send_array_data")
Call<StartResponseModal> postData(@Field("user_id") String user_id,
                                             @Field("location_data") String 
jsonObject);

then in your MainActivity.class.

 ArrayList<JSONObject> obj_arr;
 try {
                JSONArray jsonArray = new JSONArray();
                obj_arr = new ArrayList<>();
                 // LocationData is model class. 
                for (LocationData cart : arrayList) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("latitude", cart.getLatitude());
                    jsonObject.put("longitude", cart.getLongitude());
                    jsonObject.put("address", cart.getAddress());
                    jsonObject.put("battery", cart.getBattery());
                    jsonObject.put("is_gps_on", cart.getIs_gps_on());
                    jsonObject.put("is_internet_on", cart.getIs_internet_on());
                    jsonObject.put("type", cart.getType());
                    jsonObject.put("date_time", cart.getDate_time());
                    jsonArray.put(jsonObject);
                    obj_arr.add(jsonObject);
                }
                Log.e("JSONArray", String.valueOf(jsonArray));
            } catch (JSONException jse) {
                jse.printStackTrace();
            }




 String user_id = SharedPreferenceUtils.getString(getActivity(), 
 Const.USER_ID);
    RetrofitAPI retrofitAPI = 
 APIClient.getRetrofitInstance().create(RetrofitAPI.class);
    Call<StartResponseModal> call = 
 retrofitAPI.postData(user_id,obj_arr.toString());
    call.enqueue(new Callback<StartResponseModal>() {
        @Override
        public void onResponse(Call<StartResponseModal> call, 
  Response<StartResponseModal> response) {
            // Handle success
            if (response.isSuccessful() && 
  response.body().getErrorCode().equals("0")) {
                // Process the response here
                Log.e("Hello Room data send","Success");
                deleteItemsFromDatabase();


            } else {
                // Handle API error
                Log.e("Hello Room data send","failed else");

            }
        }

        @Override
        public void onFailure(Call<StartResponseModal> call, Throwable t) {
            // Handle failure
            Log.e("Hello Room send","failure");

        }
    });

Upvotes: 0

Jakegarbo
Jakegarbo

Reputation: 1301

I encounter same issue solve this by adding this dependencies:

implementation 'com.squareup.retrofit2:converter-scalars:$version'

There are multiple existing Retrofit converters for various data formats. You can serialize and deserialize Java objects to JSON or XML or any other data format and vice versa. Within the available converters, you’ll also find a Retrofit Scalars Converter that does the job of parsing any Java primitive to be put within the request body. Conversion applies to both directions: requests and responses. https://futurestud.io/tutorials/retrofit-2-how-to-send-plain-text-request-body

then you can use your generateParkingspaceBody as value to post.

generateParkingspaceBody.toString()  as your request body 

Upvotes: 0

W.K.S
W.K.S

Reputation: 10095

You don't need to convert your object to a JSONArray, Retrofit will do it automatically for you.

Simply change your API method declaration to:

@Headers({
        "Content-type: application/json"
})
Response getNearByParkingSpaces(@Header("Authorization") String accessToken,
                                    @Body List<String> arrayOfSids);

Upvotes: 18

Related Questions