改造:无法为类创建@Body转换器

2022-09-01 16:34:35

我需要通过改造2发送下一个json:

{
    "Inspection": {
        "UUID": "name",
        "ModifiedTime": "2016-03-09T01:13",
        "CreatedTime": "2016-03-09T01:13",
        "ReviewedWith": "name2",
        "Type": 1,
        "Project": {
            "Id": 41
        },
        "ActionTypes": [1]
    }   
}

带标头:Authorization: access_token_value

我试过这个:

//header parameter
String accessToken = Requests.getAccessToken();

JsonObject obj = new JsonObject();
JsonObject inspection = new JsonObject();

inspection.addProperty("UUID","name");
inspection.addProperty("ModifiedTime","2016-03-09T01:13");
inspection.addProperty("CreatedTime","2016-03-09T01:13");
inspection.addProperty("ReviewedWith","name2");
inspection.addProperty("Type","1");

JsonObject project = new JsonObject();
project.addProperty("Id", 41);

inspection.add("Project", project);
obj.add("Inspection", inspection);

Retrofit restAdapter = new Retrofit.Builder()
        .baseUrl(Constants.ROOT_API_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .addConverterFactory(ScalarsConverterFactory.create())
        .build();
IConstructSecureAPI service = restAdapter.create(IConstructSecureAPI.class);
Call<JsonElement> result = service.addInspection(accessToken, obj);
JsonElement element = result.execute().body();

但每次我收到异常:java.lang.IllegalArgumentException: Unable to create @Body converter for class com.google.gson.JsonObject (parameter #2)

我该如何发送?或者任何其他想法,我怎么能做到这一点。您甚至可以向我提供参数,例如内部的json。它将适合我String


答案 1

解决方案:在接口中声明正文值,下一步:

@Body RequestBody body并包装字符串 JSON 对象:

RequestBody body = RequestBody.create(MediaType.parse("application/json"), obj.toString());


答案 2

您可以在创建类似如下的改造时指定转换器

Retrofit retrofit = new Retrofit.Builder()
        .addConverterFactory(GsonConverterFactory.create())
        .baseUrl(baseurl)
        .client(okHttpClient)
        .build();