json post-body帮助,使用改装和jsonObject



尽管这个json看起来很简单,但我无法将其正确格式化以在正文中发布。

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

以下是我迄今为止在安卓工作室中使用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);

在客户端类中,我有

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

所以请求就像这个

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"}]}}

非常接近,但我不太明白如何使其具有预期的array/json格式??希望有人对Android和jsonObject有足够的了解。

您没有添加json数组请求

请尝试以下操作。

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);

最新更新