sectechengr
sectechengr

Reputation: 15

json post body help, using retrofit and jsonObject

As simple as this json looks I cannot get it formatted correctly to post in body.

{
    "requests": [
        {
            "action": "reject",
            "justification": "admin reason",
            "requestId": "ee4a5b4f3af54d849a63e305c13f6c8d"
        }
    ],
    "justification": "admin reason"
}

Here is what I have so far in Android studio using retrofit2

Gson gson = new GsonBuilder()
    .setLenient()
    .create();
Retrofit.Builder builder = new Retrofit.Builder()
    .baseUrl("https://myurl.com/")
    .addConverterFactory(GsonConverterFactory.create(gson));
JsonObject jsonObject = new JsonObject();
JsonObject jsonObjectN = new JsonObject();
jsonObject.addProperty("action", action);
jsonObject.addProperty("request_id", request_id);
jsonObject.addProperty("justification", "blablabla");
jsonObjectN.add("requests", jsonObject);
jsonObjectN.addProperty("justification", justification);
Retrofit retrofit = builder.build();
Client client = retrofit.create(Client.class);
Call<PostRequest> user = client.postRequests(jsonObjectN);

In client class I have

@Headers("Content-Type: application/json")
@POST("/requests")
Call<PostRequest> postRequests(@Body JsonObject body

);

So the request is like this

Request{method=POST, url=https://myurl.com/v1.0/approver/requests, tags={class retrofit2.Invocation=com.loginci.rgcislogin.Client.postRequests() [{"requests":{"action":"reject","request_id":"23423423refsdsdgdg","justification":"blablabla"},"justification":"Action done by Admin"}]}}

Very close but I cant quite figure out how to make it in the exact array/json format as its expecting?? Hopefully someone knows Android and jsonObject well enough to help.

Upvotes: 1

Views: 80

Answers (1)

Shantanu
Shantanu

Reputation: 692

You are not adding a json array request

Try the following.

Gson gson = new GsonBuilder()
    .setLenient()
    .create();
Retrofit.Builder builder = new Retrofit.Builder()
    .baseUrl("https://myurl.com/")
    .addConverterFactory(GsonConverterFactory.create(gson));
JsonObject jsonObject = new JsonObject();
JsonObject jsonObjectN = new JsonObject();
JsonArray jsonArray = new JsonArray();
jsonObject.addProperty("action", action);
jsonObject.addProperty("request_id", request_id);
jsonObject.addProperty("justification", "blablabla");
jsonArray.add(jsonObject);
jsonObjectN.add("requests", jsonArray);
jsonObjectN.addProperty("justification", justification);
Retrofit retrofit = builder.build();
Client client = retrofit.create(Client.class);
Call<PostRequest> user = client.postRequests(jsonObjectN);

Upvotes: 1

Related Questions