Rajesh
Rajesh

Reputation: 86

Array as parameter in retrofit

I have an issue with my parameters passing in retrofit, My problem is need to send int array ([3,1,2]) as one of the parameters in a POST method with retrofit 2, other parameters are as string. (ex: tips - "10", amount-"100", service-ids -[3,1,2]). How can send parameters like above in example.

Upvotes: 0

Views: 1702

Answers (2)

silent_coder14
silent_coder14

Reputation: 583

You can use ArrayList such as:

@FormUrlEncoded
    @POST("service_name") 
       void functionName(
            @Field("yourarray[]") ArrayList<String> learning_objective_uuids, @Field("user_uuids[]") ArrayList<String> user_uuids, @Field("note") String note,
            Callback<CallBackClass> callback
        );

You can follow this link.

Or you could use JSONObject like so:

@POST("demo/rest/V1/customer")
Call<RegisterEntity> customerRegis(@Body JsonObject registrationData);

registrationData:

private static JsonObject generateRegistrationRequest() {
        JSONObject jsonObject = new JSONObject();
        try {
            JSONObject subJsonObject = new JSONObject();
            subJsonObject.put("email", "[email protected]");
            subJsonObject.put("firstname", "abc");
            subJsonObject.put("lastname", "xyz");

            jsonObject.put("customer", subJsonObject);
            jsonObject.put("password", "password");

        } catch (JSONException e) {
            e.printStackTrace();
        }
        JsonParser jsonParser = new JsonParser();
        JsonObject gsonObject = (JsonObject) jsonParser.parse(jsonObject.toString());
        return gsonObject;
    }

Upvotes: 2

Wang
Wang

Reputation: 1038

You can define an object reflecting the structure of the POST body:

@POST("/pathtopostendpoint")
Call<ResponseObject> postFunction(@Body final RequestBody body);

with your RequestBody being defined as following (if you use the GSON converter, tweak the naming of the field with @SerializedName):

class RequestBody {

    String tips;
    String amount;
    int[] serviceIds;

    RequestBody(final String tips, final amount String, final int[] serviceIds) {
        this.tips = tips;
        this.amount = amount;
        this.serviceIds = serviceIds;
    }
}

and build the request call like that:

final Call<ResponseObject> call = retrofitService.postFunction(
    new RequestBody("10", "100", new int[]{ 3, 1, 2 })
);

Upvotes: 0

Related Questions