改造2反序列化错误

retrofit 2 deserialization error

我目前正在尝试对“https://hummingbirdv1.p.mashape.com”进行简单的 GET 调用,并且我正在使用 JacksonConverterFactory。我得到的错误是:

com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token

我一直在阅读堆栈溢出,这似乎是 jackson 和我的 POJO 没有被正确读取的问题。虽然如果我使用普通的默认 Jackson 核心而不是改造附带的 JacksonConverterFactory,它似乎解析得很好。

我的 POJO(我遗漏了所有可打包的方法以及 getter 和 setter)

public class ListItem implements Parcelable {

private int id;
private int mal_id;
private String slug;
private String status;
private String url;
private String title;
private String alternate_title;
private int episode_count;
private int episode_length;
private String cover_image;
private String synopsis;
private String show_type;
private String started_airing;
private String finished_airing;
private float community_rating;
private String age_rating;
private ArrayList<Name> genres;

public ListItem() {
}

public ListItem(int id, int mal_id, String slug, String status, String url, String title, String alternate_title, int episode_count, int episode_length, String cover_image, String synopsis,
                String show_type, String started_airing, String finished_airing, float community_rating, String age_rating, ArrayList<Name> genres) {
    this.id = id;
    this.mal_id = mal_id;
    this.slug = slug;
    this.status = status;
    this.url = url;
    this.title = title;
    this.alternate_title = alternate_title;
    this.episode_count = episode_count;
    this.episode_length = episode_length;
    this.cover_image = cover_image;
    this.synopsis = synopsis;
    this.show_type = show_type;
    this.started_airing = started_airing;
    this.finished_airing = finished_airing;
    this.community_rating = community_rating;
    this.age_rating = age_rating;
    this.genres = genres;
}

我要解析的示例响应是:

{


"id": 1,
  "mal_id": 1,
  "slug": "cowboy-bebop",
  "status": "Finished Airing",
  "url": "https://hummingbird.me/anime/cowboy-bebop",
  "title": "Cowboy Bebop",
  "alternate_title": "",
  "episode_count": 26,
  "episode_length": 24,
  "cover_image": "https://static.hummingbird.me/anime/poster_images/000/000/001/large/hNSma.jpg?1431697256",
  "synopsis": "Enter a world in the distant future, where Bounty Hunters roam the solar system. Spike and Jet, bounty hunting partners, set out on journeys in an ever struggling effort to win bounty rewards to survive.\r\nWhile traveling, they meet up with other very interesting people. Could Faye, the beautiful and ridiculously poor gambler, Edward, the computer genius, and Ein, the engineered dog be a good addition to the group?",
  "show_type": "TV",
  "started_airing": "1998-04-03",
  "finished_airing": "1999-04-24",
  "community_rating": 4.48547657328022,
  "age_rating": "R17+",
  "genres": [
    {
      "name": "Action"
    },
    {
      "name": "Adventure"
    },
    {
      "name": "Comedy"
    },
    {
      "name": "Drama"
    },
    {
      "name": "Sci-Fi"
    },
    {
      "name": "Space"
    }
  ]
}

使用Retrofit的服务:

AnimeRequestService {
public static String MASHAPE_BASE_URL = "https://hummingbirdv1.p.mashape.com";
private static String MASHAPE_DEBUG_KEY = "()*&#()$*)#(&*$)@(#&*$";
private final MashapeService mashapeService;
private final String TAG = AnimeRequestService.class.getCanonicalName();


public AnimeRequestService() {
    OkHttpClient client = new OkHttpClient();
    client.networkInterceptors().add(new Interceptor() {
        @Override
        public com.squareup.okhttp.Response intercept(Chain chain) throws IOException {
            chain.request().newBuilder().addHeader("Accept", "application/json");
            Request request = chain.request().newBuilder().addHeader("X-Mashape-Key", MASHAPE_DEBUG_KEY).addHeader("accept", "application/json").build();
            return chain.proceed(request);
        }
    });

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(MASHAPE_BASE_URL)
            .addConverterFactory(JacksonConverterFactory.create())
            .client(client)
            .build();

    mashapeService = retrofit.create(MashapeService.class);

}


public interface MashapeService {
    @GET("/anime/{id}")
    Call<List<ListItem>> fetchList(@Path("id") int id);
}

public void callService(int id) {
        Call<List<ListItem>> call = mashapeService.fetchList(id);
        call.enqueue(new Callback<List<ListItem>>() {
            @Override
            public void onResponse(Response<List<ListItem>> response, Retrofit retrofit) {
                for (ListItem listItem : response.body()) {
                    Log.i(TAG, listItem.getTitle());
                }
            }

            @Override
            public void onFailure(Throwable t) {
                Log.i(TAG,t.toString());
            }
        });

}

谁能看出为什么解析会从 JacksonConverterFactory 而不是 Jackson 核心失败?

看起来您正在尝试反序列化一个数组,但您只得到一个 json 对象。尝试更新您的调用以查找对象而不是列表。

public interface MashapeService {
    @GET("/anime/{id}")
    Call<ListItem> fetchList(@Path("id") int id);
}

public void callService(int id) {
        Call<ListItem> call = mashapeService.fetchList(id);
        call.enqueue(new Callback<ListItem>() {
            @Override
            public void onResponse(Response<ListItem> response, Retrofit retrofit) {
                for (ListItem listItem : response.body()) {
                    Log.i(TAG, listItem.getTitle());
                }
            }

            @Override
            public void onFailure(Throwable t) {
                Log.i(TAG,t.toString());
            }
        });

}