Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

retrofit 2 - how to pass a POST json object

Tags:

android

gson

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?

like image 369
LMaker Avatar asked May 08 '17 17:05

LMaker


1 Answers

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.

like image 59
LMaker Avatar answered Oct 22 '22 05:10

LMaker