9

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?

LMaker
  • 1,444
  • 3
  • 25
  • 38

3 Answers3

10

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) {
    }
});
Sathish Kumar VG
  • 2,154
  • 1
  • 12
  • 19
10

I saw this question that I made 1 year ago and I`m using another solution nowdays. If someone still needs a help and looking for this, here we go:

I have made a function to handle the JSON format that I want:

 public String serialize(List<Object> objects, String arrKey, String 
     objKey) {
    JsonArray ja = new JsonArray();
    for (Object object: objects) {
        Gson gson = new Gson();
        JsonElement je = gson.toJsonTree(object);
        JsonObject jo = new JsonObject();
        jo.add(objKey, je);
        ja.add(jo);
    }

    JsonObject objMain = new JsonObject();
    objMain.add(arrKey,ja);

    return objMain.toString();

}

And in my API Call I have this line:

     String json = new CustomGsonAdapter().serialize(surveysList, "surveys","survey");
    RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);

RequestBody is the trick. Now, just need to pass this RequestBody to retrofit call and thats it.

@POST("surveys")
Call<Void> setSurveys(@Body RequestBody json);

I dont know if this is the best way to archieve the problem, but for me it was. Save time and avoid to create a class just to send to server.

LMaker
  • 1,444
  • 3
  • 25
  • 38
5
@POST("users/new")
Call<User> createUser(@Body User user);

above code will be written in Api Service Interface. and then you can call this from RestClient class(by Retrofit instance) by passing a JsonObject as Body.

Ankit Mehta
  • 4,251
  • 4
  • 19
  • 27