LMaker LMaker - 27 days ago 14
Android Question

retrofit 2 - how to pass a POST json object

So, i have a List of my custom Object and I need a JSON like this:

{
"surveys": [{
"survey": {
"code": "05052017153632",
"date": "05/05/2017 15:36:32",
"device_id": 1,
"questions_attributes": [{
"kind": "string",
"label": "Você encontrou tudo o que procurava?",
"value": "Infelizmente, não"
}, {
"kind": "string",
"label": "Em qual departamento você não encontrou o produto?",
"value": "FERRAMENTAS, TAPETES"
}, {
"kind": "string",
"label": "Deseja que a Havan entre em contato com você?",
"value": "Não informado"
}, {
"kind": "string",
"label": "Nome",
"value": "Não informado"
}, {
"kind": "string",
"label": "E-mail",
"value": "Não informado"
}, {
"kind": "string",
"label": "Telefone",
"value": "Não informado"
}]
}
}]}


But I dont have any ideia how to do it using Gson.
I'm Using Retrofit 2 and need to pass this JSON into a body request.
Any ideias?

Answer Source

Yes you need to pass this JSON into body request.

Retrofit Interface:

public interface RetrofitInterface<R extends RetrofitClass> {
    @Headers({"Content-Type: application/json", "Cache-Control: max-age=640000"})
    @POST("v1/auth/")

 public Call<ResponseBody> callLogin(@Query("key") String key, @Body LoginModel body);
    @Headers({"Content-Type: application/json", "Cache-Control: max-age=640000"})

    public static final Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(AppConstants.mBaseUrl)
            .addConverterFactory(GsonConverterFactory.create())
            .build();
}

Api call Activity:

pass json object into body request use @Body param.

Here you can create gson model classes in http://www.jsonschema2pojo.org/ json to gson converter by using that json request format.

After that set values with that gson pojo classes and pass the json object to body request in retrofit.

For example:

LoginModel:

public class LoginModel {
    @SerializedName("username")
    private String username;
    @SerializedName("password")
    private String password;
public String getUsername() {
    return username;
}
public void setUsername(String username) {
    this.username = username;
}
public String getPassword() {
    return password;
}
public void setPassword(String password) {
    this.password = password;
}
}

set Values with pojo class:

LoginModel model_obj = new LoginModel();
    mModel_obj.setUsername(mUsername);
    mModel_obj.setPassword(mPassword);

Api calling:

Call<ResponseBody> call = service.callLogin(AppConstants.mApiKey, model_obj);
call.enqueue(new Callback<ResponseBody>() {
    @Override
    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
    }
    @Override
    public void onFailure(Call<ResponseBody> call, Throwable t) {
    }
});