Retrofit2 Android:BEGIN_ARRAY가 필요한데 1행 2패스 $에 BEGIN_OBJECT가 있었습니다.
누군가가 이 문제에 대해 물어보는 것이 이번이 처음이 아니라는 것을 알지만, Retrofit2를 사용해도 제 문제에 대한 적절한 해결책을 찾을 수 없습니다.온라인 튜토리얼을 따라 했는데 잘 작동했어요.내 엔드포인트에 동일한 코드를 적용하면 다음과 같은 예외가 발생합니다.java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $
어떻게 해결해야 할지 모르겠어요.
인터페이스:
public interface MyApiService {
// Is this right place to add these headers?
@Headers({"application-id: MY-APPLICATION-ID",
"secret-key: MY-SECRET-KEY",
"application-type: REST"})
@GET("Music")
Call<List<Music>> getMusicList();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(MySettings.REST_END_POINT)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
클라이언트 코드:
MyApiService service = MyApiService.retrofit.create(MyApiService.class);
Call<List<Music>> call = service.getMusicList();
call.enqueue(new Callback<List<Music>>() {
@Override
public void onResponse(Call<List<Music>> call, Response<List<Music>> response) {
Log.e("MainActivity", response.body().
}
@Override
public void onFailure(Call<List<Music>> call, Throwable t) {
Log.e("MainActivity", t.toString());
}
});
이 코드는 다음 페이로드와 함께 작동합니다.
[
{
"login": "JakeWharton",
"id": 66577,
"avatar_url": "https://avatars.githubusercontent.com/u/66577?v=3",
"gravatar_id": "",
"url": "https://api.github.com/users/JakeWharton",
"html_url": "https://github.com/JakeWharton",
"followers_url": "https://api.github.com/users/JakeWharton/followers",
"following_url": "https://api.github.com/users/JakeWharton/following{/other_user}",
"gists_url": "https://api.github.com/users/JakeWharton/gists{/gist_id}",
"starred_url": "https://api.github.com/users/JakeWharton/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/JakeWharton/subscriptions",
"organizations_url": "https://api.github.com/users/JakeWharton/orgs",
"repos_url": "https://api.github.com/users/JakeWharton/repos",
"events_url": "https://api.github.com/users/JakeWharton/events{/privacy}",
"received_events_url": "https://api.github.com/users/JakeWharton/received_events",
"type": "User",
"site_admin": false,
"contributions": 741
},
{....
하지만 이건 아니야:
{
"offset": 0,
"data": [
{
"filename": "E743_1458662837071.mp3",
"created": 1458662854000,
"publicUrl": "https://api.backendless.com/dbb77803-1ab8-b994-ffd8-65470fa62b00/v1/files/music/E743_1458662837071.mp3",
"___class": "Music",
"description": "",
"likeCount": 0,
"title": "hej Susanne. ",
"ownerId": "E743756F-E114-6892-FFE9-BCC8C072E800",
"updated": null,
"objectId": "DDD8CB3D-ED66-0D6F-FFA5-B14543ABC800",
"__meta": "{\"relationRemovalIds\":{},\"selectedProperties\":[\"filename\",\"created\",\"publicUrl\",\"___class\",\"description\",\"likeCount\",\"title\",\"ownerId\",\"updated\",\"objectId\"],\"relatedObjects\":{}}"
},
{...
마이 뮤직 클래스:
public class Music {
private String ownerId;
private String filename;
private String title;
private String description;
private String publicUrl;
private int likeCount;
// Getters & Setters
}
"이 코드는 이 페이로드와 함께 작동합니다.하지만 이건 아니야:.."그건 예상된 일이며, 그렇게 작동해야 합니다.실제로 오류 메시지는 json을 java 객체로 변환하는 동안 콜이 json의 배열을 예상했지만 대신 객체를 얻었음을 나타냅니다.
문의처:
@GET("Music")
Call<List<Music>> getMusicList();
리스트를 기대하다Music
오브젝트, 그래서 json에서 동작합니다.
[
{
"login": "JakeWharton",
...
},
...
]
왜냐하면 json 자체는 당신의 배열이기 때문입니다.Music
오브젝트(재적합은 json 어레이 간에 Java 목록으로 변환할 수 있습니다).두 번째 json의 경우 어레이가 아닌 객체만 있습니다(이러한 json의 부족에 주의).[...]
이를 위해서는 해당 json에 매핑되는 다른 모델을 사용하여 다른 콜을 작성해야 합니다.예를 들어, 당신이 모델명을MusicList
문의는 다음과 같습니다.
@GET("Music")
Call<MusicList> getMusicList();
(첫 번째 콜과 이 콜을 모두 유지할 경우 메서드 이름을 변경해야 할 수 있습니다).
그MusicList
모델은 다음과 같습니다.
public class MusicList {
@SerializedName("data")
private List<Music> musics;
// ...
}
제 생각엔data
array는 다음 목록입니다.Music
근데 jsons가 완전히 다르다는 걸 알았어요.이것도 수정해야 할 것 같은데, 여기 상황을 알 수 있을 것 같아요.
이런 문제가 있었어요.payload가 객체 배열이 아니라 객체이기 때문입니다.그래서 리스트를 삭제했습니다.
코드 예시
UserAPI.java
public interface UserAPI {
@GET("login/cellphone")
Call<LoginResponse> login(@Query("phone") String phone,
@Query("password") String password);
}
콜코드
Retrofit retrofit = new Retrofit
.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(Constant.CLOUD_MUSIC_API_BASE_URL)
.build();
UserAPI userAPI = retrofit.create(UserAPI.class);
userAPI.login(phone, password).enqueue(new Callback<LoginResponse>() {
@Override
public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
System.out.println("onResponse");
System.out.println(response.body().toString());
}
@Override
public void onFailure(Call<LoginResponse> call, Throwable t) {
System.out.println("onFailure");
System.out.println(t.fillInStackTrace());
}
});
내 경우 이 함수의 반환 유형이 잘못되어 반환되는 것이 문제였습니다.retrofit2.Call<List<GamesModel>>
이 에러는, GSON이 서버로부터 어레이가 돌아오는 것을 상정하고 있는 것을 의미합니다.
목록을 삭제하기만 하면 정상적으로 작동합니다.
언급URL : https://stackoverflow.com/questions/36177629/retrofit2-android-expected-begin-array-but-was-begin-object-at-line-1-column-2
'programing' 카테고리의 다른 글
Null이 아닌 속성이 과도 값을 참조함 - 현재 작업 전에 임시 인스턴스를 저장해야 합니다. (0) | 2023.04.01 |
---|---|
Woocommerce 리셋 패스워드가 기능하지 않음 (0) | 2023.04.01 |
스프링 부트와 스프링 IO의 관계는 무엇입니까? (0) | 2023.04.01 |
스프링을 사용하여 Eureka 디스커버리 클라이언트를 선택적으로 비활성화하려면 어떻게 해야 합니까? (0) | 2023.04.01 |
Yoast SEO | 커스텀 변수 작성 방법 (0) | 2023.04.01 |