繁体   English   中英

无法在 Android Retrofit 中为我的 class 创建转换器

[英]Unable to create converter for my class in Android Retrofit

我正在尝试使用 Retrofit 开发客户端服务器应用程序。 我的应用程序使用字符串“image”发送到服务器 json,并使用带有字段“name”的字符串响应 json。

我的 API:

public interface API {
    @FormUrlEncoded
    @POST("/api/classification/imagenet")
    Call<GestureJson> getName(@Body ImageJson json);
}

图像Json:

public class ImageJson {
    public String imageString;
}

姓名Json:

public class NameJson {
    public int gestureNumber;
}

当用户按下 Main Activity MyVoid 中的按钮时(url 已知):

public void MyVoid() {
        String requestUrl = url;
        Retrofit retrofit = new Retrofit.Builder()
                .addCallAdapterFactory(GsonConverterFactory.create())
                .baseUrl(requestUrl)
                .build();
        API api = retrofit.create(API.class);
        ImageJson json = new ImageJson();
        json.imageString = image_uri.toString();
        Call<GestureJson> call = api.getName(json);
        call.enqueue(new Callback<GestureJson>() {
            @Override
            public void onResponse(Call<GestureJson> call, Response<GestureJson> response) {
                if (response.isSuccessful()) {
                    status = RESPONSE_SUCCESS;
                } else {
                    status = RESPONSE_FAIL;
                }
            }

            @Override
            public void onFailure(Call<GestureJson> call, Throwable t) {

            }
        });

我有三个问题:

1)我不知道Retrofit和Retrofit2有什么区别。 用什么比较好?

2).addCallAdapterFactory(GsonConverterFactory.create()) 强调了错误的程度(在 Retorfit 和 Retrofit2 中)。

3) 如果我删除.addCallAdapterFactory(GsonConverterFactory.create()),我可以编译应用程序。 但我有一个问题:

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.opencvproject, PID: 17742
java.lang.IllegalArgumentException: Unable to create converter for class com.example.opencvproject.GestureJson
    for method API.getGesture
  1. Retrofit2 更好,因为 Retrofit 已过时(最后一个版本是在 2014 年https://github.com/square/retrofit/releases/tag/parent-1.6.0 )。 名称中的 2 号只是一个库版本。
  2. GsonConverterFactory 可能会加下划线,因为您没有添加依赖com.squareup.retrofit2:converter-gson
  3. 如果删除addCallAdapterFactory(GsonConverterFactory.create())则 Retrofit 将不知道如何将 json 反序列化为对象。 GsonConverterFactory 在后台使用 Gson 库( https://github.com/google/gson )反序列化服务器 json 响应。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM