gpt4 book ai didi

java - 我如何在 Retrofit 库中使用 Gson?

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:54:07 25 4
gpt4 key购买 nike

我使用 Retrofit 发送请求并在 android 中接收响应,但是当我想要转换来自服务器的响应时遇到问题,它总是给我 Exception:

retrofit.RetrofitError: com.google.gson.JsonSyntaxException: 
java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING

当服务器的响应应该给我电影列表时,我需要将所有这些电影放入列表中。

电影(模型类):

public class Movie {
public Movie() {}
@SerializedName("original_title")
private String movieTitle;
@SerializedName("vote_average")
private String movieVoteAverage;
@SerializedName("overview")
private String movieOverview;
............
}

GitMovieApi 类:

public interface GitMovieApi {
@GET("/3/movie/{movie}")
public void getMovie(@Path("movie") String typeMovie,@Query("api_key") String keyApi, Callback<Movie> response);
}

RestAdapter 配置:

RestAdapter restAdapter = new RestAdapter.Builder()
.setLogLevel(RestAdapter.LogLevel.FULL)
.setConverter(new GsonConverter(new GsonBuilder().registerTypeAdapter(Movie.class, new UserDeserializer()).create()))
.setEndpoint("http://api.themoviedb.org")
.build();
GitMovieApi git = restAdapter.create(GitMovieApi.class);
git.getMovie("popular", "Keyapi", new Callback<Movie>() {
@Override
public void success(Movie movie, Response response) {
Toast.makeText(getActivity(), "s", Toast.LENGTH_LONG).show();
}
@Override
public void failure(RetrofitError error) {
Toast.makeText(getActivity(), error.getMessage(), Toast.LENGTH_LONG).show();
}
});

用户解串器:

public class UserDeserializer implements JsonDeserializer<Movie> {
@Override
public Movie deserialize(JsonElement jsonElement, Type typeOF,
JsonDeserializationContext context)
throws JsonParseException {
JsonElement userJson = new JsonParser().parse("results");
return new Gson().fromJson(userJson, Movie.class);
}
}

Json(响应):

{
"page": 1,
"results": [
{
"adult": false,
"backdrop_path": "/tbhdm8UJAb4ViCTsulYFL3lxMCd.jpg",
"genre_ids": [
53,
28,
12
],
"id": 76341,
"original_language": "en",
"original_title": "Mad Max: Fury Road",
"overview": "An apocalyptic story set in the furthest.",
"release_date": "2015-05-15",
"poster_path": "/kqjL17yufvn9OVLyXYpvtyrFfak.jpg",
"popularity": 48.399601,
"title": "Mad Max: Fury Road",
"video": false,
"vote_average": 7.6,
"vote_count": 2114
},
{
"adult": false,
"backdrop_path": "/sLbXneTErDvS3HIjqRWQJPiZ4Ci.jpg",
"genre_ids": [
10751,
16,
12,
35
],
"id": 211672,
"original_language": "en",
"original_title": "Minions",
"overview": "Minions Stuart.",
"release_date": "2015-06-25",
"poster_path": "/s5uMY8ooGRZOL0oe4sIvnlTsYQO.jpg",
"popularity": 31.272707,
"title": "Minions",
"video": false,
"vote_average": 6.8,
"vote_count": 1206
},
],
"total_pages": 11871,
"total_results": 237415
}

最佳答案

您甚至不需要在这里制作自定义反序列化器。

完全摆脱 UserDeserializer,它不是必需的。您的查询返回的是电影列表,因此请回调一个实际读取电影列表的对象:

public class MovieList {
@SerializedName("results")
List<Movie> movieList;
// you can also add page, total_pages, and total_results here if you want
}

那么您的 GitMovieApi 类将是:

public interface GitMovieApi {
@GET("/3/movie/{movie}")
public void getMovie(@Path("movie") String typeMovie,
@Query("api_key") String keyApi,
Callback<MovieList> response);
}

您的RestAdapter:

RestAdapter restAdapter = new RestAdapter.Builder()
.setLogLevel(RestAdapter.LogLevel.FULL)
.setConverter(new GsonConverter(new GsonBuilder()).create()))
.setEndpoint("http://api.themoviedb.org")
.build();
GitMovieApi git = restAdapter.create(GitMovieApi.class);

问题是不是你写错了Deserializer(虽然,你写了,但没关系,因为你不需要它,JsonParser 不是你是怎么做的),但默认的反序列化行为应该适合你。使用上面的代码,它会工作得很好。

关于java - 我如何在 Retrofit 库中使用 Gson?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32490011/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com