1

i would like to post an array of objects along with other kind of formdata.

Something like

{
  country: "us",
  province: "ny",
  cities: [{
    name: "hello",
    size: "small"
  }, {
    name: "hi",
    size: "big"
  }]
}

How do I do this in retrofit? I only need the part where it is declaring the retrofit client api.

@FormUrlEncoded
@PUT("user/doStuff")
Observable<Void> doStuff(@Field("country") String country, @Field("province") String province,
/* What do i do with cities here?? */);

1 Answer 1

3

You can try something like this, but depends how server is configured.

public class City {
    @SerializedName("city")
    public String city;

    @SerializedName("size")
    public String size;
}

public class ObjectToSend {
    @SerializedName("country")
    public String country;

    @SerializedName("province")
    public String province;

    @SerializedName("cities")
    public List<City> cities;
}


@PUT("user/doStuff")
Observable<Void> doStuff(@Body ObjectToSend object);
Sign up to request clarification or add additional context in comments.

4 Comments

This will work. But is there a way to do it generically? Say. Is it possible to pass an JSONObject[] as cities ?
What do you mean in "generically"? Gson is faster than JsonObject. And if you use retrofit with rxjava, is recommended to use like this, my example. It will work like a charm.
For example. My "user/doStuff" api will actually accept a different range of objects. Is it possible to have this retrofit thing to also accept a generic type like JSONObject. And then in my application. I can just invoke some method to convert my object into jsonObject and then i can pass them over.
You can try to convert them to string, idk. Retrofit is more specific object oriented. In the end, entire object that you want to send will become a string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.