我从使用Volley迁移到改型,我已经有了gson类,以前我用它将JSONObject Response转换为实现gson注释的对象.当我试图使用改型发出http get请求,但我的应用程序因以下错误而崩溃时:

 Unable to start activity ComponentInfo{com.lightbulb.pawesome/com.example.sample.retrofit.SampleActivity}: java.lang.IllegalArgumentException: Unable to create converter for class com.lightbulb.pawesome.model.Pet
    for method GitHubService.getResponse

我正在遵循retrofit站点的指南,我想出了以下实施方案:

这是我试图执行retro http请求的活动:

public class SampleActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sample);

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("**sample base url here**")
                .build();

        GitHubService service = retrofit.create(GitHubService.class);
        Call<Pet> callPet = service.getResponse("41", "40");
        callPet.enqueue(new Callback<Pet>() {
            @Override
            public void onResponse(Response<Pet> response) {
                Log.i("Response", response.toString());
            }

            @Override
            public void onFailure(Throwable t) {
                Log.i("Failure", t.toString());
            }
        });
        try{
            callPet.execute();
        } catch (IOException e){
            e.printStackTrace();
        }

    }
}

我的接口,后来变成了我的API

public interface GitHubService {
    @GET("/ **sample here** /{petId}/{otherPet}")
    Call<Pet> getResponse(@Path("petId") String userId, @Path("otherPet") String otherPet);
}

最后是宠物类,应该是回应:

public class Pet implements Parcelable {

    public static final String ACTIVE = "1";
    public static final String NOT_ACTIVE = "0";

    @SerializedName("is_active")
    @Expose
    private String isActive;
    @SerializedName("pet_id")
    @Expose
    private String petId;
    @Expose
    private String name;
    @Expose
    private String gender;
    @Expose
    private String age;
    @Expose
    private String breed;
    @SerializedName("profile_picture")
    @Expose
    private String profilePicture;
    @SerializedName("confirmation_status")
    @Expose
    private String confirmationStatus;

    /**
     *
     * @return
     * The confirmationStatus
     */
    public String getConfirmationStatus() {
        return confirmationStatus;
    }

    /**
     *
     * @param confirmationStatus
     * The confirmation_status
     */
    public void setConfirmationStatus(String confirmationStatus) {
        this.confirmationStatus = confirmationStatus;
    }

    /**
     *
     * @return
     * The isActive
     */
    public String getIsActive() {
        return isActive;
    }

    /**
     *
     * @param isActive
     * The is_active
     */
    public void setIsActive(String isActive) {
        this.isActive = isActive;
    }

    /**
     *
     * @return
     * The petId
     */
    public String getPetId() {
        return petId;
    }

    /**
     *
     * @param petId
     * The pet_id
     */
    public void setPetId(String petId) {
        this.petId = petId;
    }

    /**
     *
     * @return
     * The name
     */
    public String getName() {
        return name;
    }

    /**
     *
     * @param name
     * The name
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     *
     * @return
     * The gender
     */
    public String getGender() {
        return gender;
    }

    /**
     *
     * @param gender
     * The gender
     */
    public void setGender(String gender) {
        this.gender = gender;
    }

    /**
     *
     * @return
     * The age
     */
    public String getAge() {
        return age;
    }

    /**
     *
     * @param age
     * The age
     */
    public void setAge(String age) {
        this.age = age;
    }

    /**
     *
     * @return
     * The breed
     */
    public String getBreed() {
        return breed;
    }

    /**
     *
     * @param breed
     * The breed
     */
    public void setBreed(String breed) {
        this.breed = breed;
    }

    /**
     *
     * @return
     * The profilePicture
     */
    public String getProfilePicture() {
        return profilePicture;
    }

    /**
     *
     * @param profilePicture
     * The profile_picture
     */
    public void setProfilePicture(String profilePicture) {
        this.profilePicture = profilePicture;
    }


    protected Pet(Parcel in) {
        isActive = in.readString();
        petId = in.readString();
        name = in.readString();
        gender = in.readString();
        age = in.readString();
        breed = in.readString();
        profilePicture = in.readString();
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(isActive);
        dest.writeString(petId);
        dest.writeString(name);
        dest.writeString(gender);
        dest.writeString(age);
        dest.writeString(breed);
        dest.writeString(profilePicture);
    }

    @SuppressWarnings("unused")
    public static final Parcelable.Creator<Pet> CREATOR = new Parcelable.Creator<Pet>() {
        @Override
        public Pet createFromParcel(Parcel in) {
            return new Pet(in);
        }

        @Override
        public Pet[] newArray(int size) {
            return new Pet[size];
        }
    };
}

推荐答案

2.0.0之前,默认转换器是gson转换器,但在2.0.0及更高版本中,默认转换器是ResponseBody.从文件中:

默认情况下,改型只能将HTTP主体反序列化为OkHttp主体

2.0.0+中,您需要显式指定需要一个gson转换器:

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("**sample base url here**")
    .addConverterFactory(GsonConverterFactory.create())
    .build();

您还需要将以下依赖项添加到Gradle文件:

compile 'com.squareup.retrofit2:converter-gson:2.1.0'

对转换器使用与改装相同的版本.以上内容与此改装相关性相匹配:

compile ('com.squareup.retrofit2:retrofit:2.1.0')

另外,请注意,在 compose 本文时,改装文档并未完全更新,这就是为什么该示例会给您带来麻烦.从文件中:

注:该网站仍在为新的2.0 API进行扩展.

Android相关问答推荐

超过Unity+Android磁贴内存限制,部分内容可能无法绘制

Jetpack编写日期 Select 器

使用Retrofit2的API调用:我如何能够一直进行API调用,以更新数据而无需重新打开应用程序

替换- prop -中的值(adb shell getprop)

如何将我的Android应用程序(Kotlin)中的图像分享给其他应用程序?

DocumentFile.canWrite()、DocumentFile.Existes()-使用本地内置手机存储(而不是云)时性能较差(占用太多CPU时间)

FireBase Android ChildEventListener在被规则拒绝时触发(RTDB)

判断文本视图是否为单行

更改活动(上下文)对接收到的uri的访问权限的影响?

解决失败:Landroidx/compose/runtime/PrimitiveSnapshotStateKt

仅当先前输入为 yes 时,Android 才会要求下一个输入

在 Android 房间迁移中获取上下文

CoroutineScope 与挂起函数

如何以编程方式通过 whatsapp android 共享图像和文本

找不到(包名称).在以下位置搜索:

观察软键盘可见性,打开/关闭 Jetpack Compose

喷气背包组成影子奇怪的行为

Android 12 通过包管理器中断 APK 安装?

我的 react native 项目的发布签名 apk 没有在设备中打开,而且它创建的尺寸非常小

TextField 溢出和软包装不适用于 Compose 约束布局