json Retrofit:无法为类创建@Body转换器

r8uurelv  于 2023-02-10  发布在  其他
关注(0)|答案(9)|浏览(175)

我需要通过改型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)
我该怎么发送呢?或者我该怎么做呢?你甚至可以给我提供一个简单的参数,比如String里面有json,它会适合我的

au9on6nz

au9on6nz1#

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

@Body RequestBody body并 Package 字符串JSON对象:
RequestBody body = RequestBody.create(MediaType.parse("application/json"), obj.toString());

sdnqo3pr

sdnqo3pr2#

您有可能将同一个@SerializedName("")保存为多个vairable/fields/tags

gpnt7bae

gpnt7bae3#

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

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

zf9nrax14#

如果这是由于@SerializedName导致的,请确保其不重复。
例如,在以下情况下将抛出此错误:(注:bookingId通过两次)

@SerializedName(value="bookingId", alternate={"id", "bookingId"})

但是,这是正确的:

@SerializedName(value="bookingId", alternate={"id", "someOtherId", "whateverId"})
qxsslcnc

qxsslcnc5#

  • Body* 使用单个请求对象,请按如下方式声明请求对象
class Inspection {
    String UUID;
    //..... add your fields 
    Project project;      
}

class Product
{
   int Id;
   //....... add your fields 
}

我假设您的服务IConstructSecureAPI端点是:

@GET(...)    // change based on your api GET/POST
Call<Response> addInspection(
    @Header("Authorization") String accesstoken, 
    @Body Inspection request
);

然后你就可以说出你的愿望Response
检查这个answer,它使用HashMap代替类。

9rnv2umw

9rnv2umw6#

当我升级到Java 17时,我一直收到这个错误,在Java 11上仍然工作正常。

以下是对我有效的方法
  • 为了更深入地了解异常,我在改进堆栈跟踪中找到的Utils.java中放置了一个调试点。
  • 这样做让我想到了狭义的原因java.lang.reflect.InaccessibleObjectException: Unable to make field private final byte java.time.LocalTime.hour accessible: module java.base does not "opens java.time" to unnamed module @35e2d654
  • 从这里进一步搜索,我找到了https://github.com/mockk/mockk/issues/681#issuecomment-959646598,简单地说,它建议添加--add-opens java.base/java.time=ALL-UNNAMED作为JVM参数。
  • 嘣,成功了。
kyvafyod

kyvafyod7#

在我的例子中,我只是忘记应用Gradle的 kotlinx.serialization 插件,因此没有生成序列化器的代码。

plugins {
    kotlin("plugin.serialization")
}
jfgube3f

jfgube3f8#

您可以使用拦截器在每个请求中发送授权标头

class AuthorizationInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request originalRequest = chain.request();
        String authorizationToken = AuthenticationUtils.getToken();
        Request authorizedRequest = originalRequest.newBuilder()
            .header("Authorization", authorizationToken)
            .build();
        return chain.proceed(authorizedRequest);
    }
}
nfeuvbwi

nfeuvbwi9#

我正在使用MoshiRetrofit,我的问题是我忘记为@bodyDTO类添加@JsonSerializable注解。您应该像这样添加此注解:

@JsonSerializable
data class RegisterDTO(
    @field:Json(name = "device_id") val deviceId: String,
)

相关问题