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

neu*_*t47 11 java json retrofit retrofit2

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

{
    "Inspection": {
        "UUID": "name",
        "ModifiedTime": "2016-03-09T01:13",
        "CreatedTime": "2016-03-09T01:13",
        "ReviewedWith": "name2",
        "Type": 1,
        "Project": {
            "Id": 41
        },
        "ActionTypes": [1]
    }   
}
Run Code Online (Sandbox Code Playgroud)

带标题: 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();
Run Code Online (Sandbox Code Playgroud)

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

我该怎么发送?或者任何其他想法我怎么做.您甚至可以String通过内部的json 为我提供简单的参数.它适合我

neu*_*t47 18

解决方案: 在接口中使用next声明body值:

@Body RequestBody body 并包装String JSON对象:

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


Moh*_*sim 15

您有可能为多个变量/字段/标签保留相同的 @SerializedName("")


Ema*_*uel 13

您可以在像这样创建 Retrofit 时指定一个转换器

Retrofit retrofit = new Retrofit.Builder()
        .addConverterFactory(GsonConverterFactory.create())
        .baseUrl(baseurl)
        .client(okHttpClient)
        .build();
Run Code Online (Sandbox Code Playgroud)