Android Retrofit 라이브러리에서 수업 용 변환기를 만들 수 없습니다.
Volley를 Retrofit으로 마이그레이션하면서 이미 JSONObject 응답을 gson 주석을 구현하는 객체로 변환하는 데 사용한 gson 클래스가 있습니다. 개조를 사용하여 http 가져 오기 요청을 만들려고하지만 내 응용 프로그램 이이 오류로 충돌합니다.
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
개조 사이트 의 가이드를 따르고 있으며 이러한 구현을 생각해 냈습니다.
이것은 레트로 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);
}
그리고 마지막으로 응답해야 할 Pet 클래스 :
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
입니다. 문서에서 :
By default, Retrofit can only deserialize HTTP bodies into OkHttp's
ResponseBody
type and it can only accept itsRequestBody
type for@Body
.
In 2.0.0+
, you need to explicitly specify you want a Gson converter:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("**sample base url here**")
.addConverterFactory(GsonConverterFactory.create())
.build();
You will also need to add the following dependency to your gradle file:
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
Use the same version for the converter as you do for your retrofit. The above matches this retrofit dependency:
compile ('com.squareup.retrofit2:retrofit:2.1.0')
Also, note as of writing this, the retrofit docs are not completely updated, which is why that example got you into trouble. From the docs:
Note: This site is still in the process of being expanded for the new 2.0 APIs.
If anyone ever comes across this in the future because you are trying to define your own custom converter factory and are getting this error, it can also be caused by having multiple variables in a class with a misspelled or the same serialized name. IE:
public class foo {
@SerializedName("name")
String firstName;
@SerializedName("name")
String lastName;
}
Having serialized names defined twice (likely by mistake) will also throw this exact same error.
Update: Keep in mind that this logic also holds true via inheritance. If you extend to a parent class with an object that has the same Serialized name as you do in the sub-class, it will cause this same problem.
Based on top comment I updated my imports
implementation 'com.squareup.retrofit2:retrofit:2.1.0'
implementation 'com.squareup.retrofit2:converter-gson:2.1.0'
I've used http://www.jsonschema2pojo.org/ in order to create pojo's from Spotify json results and making sure to specify Gson format.
These days there are Android Studio plugins which can create the pojo's or Kotlin data models for you. One great option for mac is Quicktype. https://itunes.apple.com/us/app/paste-json-as-code-quicktype/id1330801220
In my case, I had a TextView object inside my modal class and GSON did not know how to serialize it. Marking it as 'transient' solved the issue.
@Silmarilos's post helped me solve this. In my case, it was that I used "id" as a serialized name, like this:
@SerializedName("id")
var node_id: String? = null
and I changed it to
@SerializedName("node_id")
var node_id: String? = null
All working now. I forgot that 'id' is a default attribute.
This may help someone
In my case mistakenly I wrote SerializedName like this
@SerializedName("name","time")
String name,time;
It should be
@SerializedName("name")
String name;
@SerializedName("time")
String time;
Hey i was going through the same issue today took me a whole day to find a solution but this is the solution i found finally. Am using Dagger in my code and i needed to implement the Gson converter in my retrofit instance.
so this was my code before
@Provides
@Singleton
Retrofit providesRetrofit(Application application,OkHttpClient client) {
String SERVER_URL=URL;
Retrofit.Builder builder = new Retrofit.Builder();
builder.baseUrl(SERVER_URL);
return builder
.client(client)
.build();
}
this was what i ended up with
@Provides
@Singleton
Retrofit providesRetrofit(Application application,OkHttpClient client, Gson gson) {
String SERVER_URL=URL;
Retrofit.Builder builder = new Retrofit.Builder();
builder.baseUrl(SERVER_URL);
return builder
.client(client)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
}
notice how there is no converter in the first example and the addition if you haven't instantiated Gson you add it like this
@Provides
@Singleton
Gson provideGson() {
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
return gsonBuilder.create();
}
and ensure you have included it in the method call for retrofit.
once again hope this helps some one like me.
In my case, it was due to trying to take a List being returned by my service into an ArrayList. So what I had was:
@Json(name = "items")
private ArrayList<ItemModel> items;
when I should've had
@Json(name = "items")
private List<ItemModel> items;
Hope this helps someone!
In my case, the problem was that my SUPERCLASS model had this field defined in it. Very stupid, I know....
'Programing' 카테고리의 다른 글
Java에서 int의 스트림을 char의 스트림으로 변환 (0) | 2020.07.22 |
---|---|
Cordova : 특정 iOS 에뮬레이터 이미지 시작 (0) | 2020.07.22 |
nil & empty의 문자열 확인 (0) | 2020.07.22 |
기존 파일을 일괄로 덮어 쓰는 방법은 무엇입니까? (0) | 2020.07.21 |
Ruby에서 File 클래스를 사용하여 디렉토리가 없으면 어떻게 디렉토리를 작성합니까? (0) | 2020.07.21 |