没有从 Retrofit 获得任何数据
Didn't get any data from Retrofit
我对 Retrofit 调用有疑问。我想获取一些数据,只是为了测试目的,看看是否有任何结果,但如您所见,没有任何结果。我得到类似 0、0.0、null 的数据。
Json 回应
{
"page": 1,
"total_results": 1295,
"total_pages": 65,
"results": [
{
"vote_count": 1669,
"id": 10515,
"video": false,
"vote_average": 8,
"title": "Castle in the Sky",
"popularity": 15.853,
"poster_path": "\/npOnzAbLh6VOIu3naU5QaEcTepo.jpg",
"original_language": "ja",
"original_title": "天空の城ラピュタ",
"genre_ids": [
12,
14,
16,
28,
10751,
10749
],
"backdrop_path": "\/fnMzL4G6HYilH1w1leFXOY5b29m.jpg",
"adult": false,
"overview": "A young boy and a girl with a magic crystal must race against pirates and foreign agents in a search for a legendary floating castle.",
"release_date": "1986-08-02"
},
{
"vote_count": 154,
"id": 487672,
"video": false,
"vote_average": 6.7,
"title": "Reign of the Supermen",
"popularity": 15.461,
"poster_path": "\/e9TzqscNRUaG8HqEP3K1jUvi8pC.jpg",
"original_language": "en",
"original_title": "Reign of the Supermen",
"genre_ids": [
16,
28,
878
],
"backdrop_path": "\/cdCMUHWyXBOsbLL4dOEPdCEtwM4.jpg",
"adult": false,
"overview": "In the wake of The Death of Superman, the world is still mourning the loss of the Man of Steel following his fatal battle with the monster Doomsday. However, no sooner as his body been laid to rest than do four new bearers of the Superman shield come forward to take on the mantle. The Last Son of Krypton, Superboy, Steel, and the Cyborg Superman all attempt to fill the vacuum left by the world's greatest champion. Meanwhile, Superman's death has also signaled to the universe that Earth is vulnerable. Can these new Supermen and the rest of the heroes prove them wrong?",
"release_date": "2019-01-13"
}
]
}
接口调用
@GET("3/discover/movie?api_key=APIKEY&with_genres=27")
Call<model> getABC();
改造调用
String url = "https://api.themoviedb.org/";
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build();
apiCall api = retrofit.create(apiCall.class);
Call<model> call = api.getABC();
call.enqueue(new Callback<model>() {
@Override
public void onResponse(Call<model> call, Response<model> response) {
if (!response.isSuccessful()){
}
List<model> list = Collections.singletonList(response.body());
for (model model : list) {
String content = "";
content += model.getVote_count() + "\n";
content += model.getVote_average() + "\n";
content += model.getOverview() + "\n\n\n";
System.out.println(content);
}
}
@Override
public void onFailure(Call<model> call, Throwable t) {
}
});
}
POJO
public class model {
@SerializedName("vote_count")
private int vote_count;
@SerializedName("vote_average")
private double vote_average;
@SerializedName("overview")
private String overview;
public int getVote_count() {
return vote_count;
}
public double getVote_average() {
return vote_average;
}
public String getOverview() {
return overview;
}
我应该在代码中更改什么?我会感激每一个提示。我从通话中收到的代码是 200 - 所以通话成功,我的 pojo class 有问题吗?
*已编辑 POJO
public class model {
@SerializedName("results")
@Expose
private List<movies> results;
public List<movies> getResults() {
return results;
}
class movies {
@SerializedName("vote_count")
@Expose
private Integer voteCount;
@SerializedName("vote_average")
@Expose
private Double voteAverage;
@SerializedName("overview")
@Expose
private String overview;
}
}
编辑改造电话
public void onResponse(Call<model> call, Response<model> response) {
if (!response.isSuccessful()){
}
List<model> list = Collections.singletonList(response.body());
for (model model : list) {
System.out.println(model.getResults());
}
}
这是我收到的部分。
com.example.x.model$movies@5f6763b,
com.example.x.model$movies@e988158,
com.example.x.model$movies@6812b1,
为什么没有正确命名?
您的模型 class 应如下所示:
public class Model {
@SerializedName("page")
private int page;
@SerializedName("results")
private List<Result> results;
@SerializedName("total_results")
private int total;
@SerializedName("total_pages")
private int totalPages;
//.......getter setter methods
}
public class Result{
@SerializedName("vote_count")
private int voteCount;
@SerializedName("vote_average")
private double voteAverage;
@SerializedName("overview")
private String overView;
//.....other fields
//......getter setter methods
}
那么改造调用应该是这样的:
Call<model> call = api.getABC();
call.enqueue(new Callback<Model>() {
@Override
public void onResponse(Call<Model> call, Response<Model> response) {
if (response.isSuccessful()) {
List<Result> results=response.body().getResults();
for(Result result:results){
Log.d(TAG,"Result: "+result.getVoteCount())
}
}
}
@Override
public void onFailure(Call<Model> call, Throwable t) {
}
});
编码愉快.... :)
使用 this 站点在 java
中生成正确的响应 class
响应 class 将如下所示:
public class BasicResponse implements Serializable
{
@SerializedName("page")
@Expose
private long page;
@SerializedName("total_results")
@Expose
private long totalResults;
@SerializedName("total_pages")
@Expose
private long totalPages;
@SerializedName("results")
@Expose
private List<Result> results = null;
private final static long serialVersionUID = 8749582078961182468L;
public long getPage() {
return page;
}
public void setPage(long page) {
this.page = page;
}
public long getTotalResults() {
return totalResults;
}
public void setTotalResults(long totalResults) {
this.totalResults = totalResults;
}
public long getTotalPages() {
return totalPages;
}
public void setTotalPages(long totalPages) {
this.totalPages = totalPages;
}
public List<Result> getResults() {
return results;
}
public void setResults(List<Result> results) {
this.results = results;
}
}
//-----------------------------------com.example.Result.java--------------
package com.example;
import java.io.Serializable;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Result implements Serializable
{
@SerializedName("vote_count")
@Expose
private long voteCount;
@SerializedName("id")
@Expose
private long id;
@SerializedName("video")
@Expose
private boolean video;
@SerializedName("vote_average")
@Expose
private double voteAverage;
@SerializedName("title")
@Expose
private String title;
@SerializedName("popularity")
@Expose
private double popularity;
@SerializedName("poster_path")
@Expose
private String posterPath;
@SerializedName("original_language")
@Expose
private String originalLanguage;
@SerializedName("original_title")
@Expose
private String originalTitle;
@SerializedName("genre_ids")
@Expose
private List<Long> genreIds = null;
@SerializedName("backdrop_path")
@Expose
private String backdropPath;
@SerializedName("adult")
@Expose
private boolean adult;
@SerializedName("overview")
@Expose
private String overview;
@SerializedName("release_date")
@Expose
private String releaseDate;
private final static long serialVersionUID = 2770789699641812364L;
public long getVoteCount() {
return voteCount;
}
public void setVoteCount(long voteCount) {
this.voteCount = voteCount;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public boolean isVideo() {
return video;
}
public void setVideo(boolean video) {
this.video = video;
}
public double getVoteAverage() {
return voteAverage;
}
public void setVoteAverage(double voteAverage) {
this.voteAverage = voteAverage;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public double getPopularity() {
return popularity;
}
public void setPopularity(double popularity) {
this.popularity = popularity;
}
public String getPosterPath() {
return posterPath;
}
public void setPosterPath(String posterPath) {
this.posterPath = posterPath;
}
public String getOriginalLanguage() {
return originalLanguage;
}
public void setOriginalLanguage(String originalLanguage) {
this.originalLanguage = originalLanguage;
}
public String getOriginalTitle() {
return originalTitle;
}
public void setOriginalTitle(String originalTitle) {
this.originalTitle = originalTitle;
}
public List<Long> getGenreIds() {
return genreIds;
}
public void setGenreIds(List<Long> genreIds) {
this.genreIds = genreIds;
}
public String getBackdropPath() {
return backdropPath;
}
public void setBackdropPath(String backdropPath) {
this.backdropPath = backdropPath;
}
public boolean isAdult() {
return adult;
}
public void setAdult(boolean adult) {
this.adult = adult;
}
public String getOverview() {
return overview;
}
public void setOverview(String overview) {
this.overview = overview;
}
public String getReleaseDate() {
return releaseDate;
}
public void setReleaseDate(String releaseDate) {
this.releaseDate = releaseDate;
}
}
您应该检查的所有步骤:
- 在邮递员或每个浏览器中调用您的 api 以 get 和 检查 响应json
- 将您的 json 响应 (您预期的) 复制到 http://www.jsonschema2pojo.org/ 此站点以获取该站点的 POJO
- 在 base URL 和 endpoint 中阻止你的 api 地址并创建改造请求
- in onResponse 改造请求回调块,如果你期望得到 json Object 所以调用这个方法
java
public static UsersPOJO getOUsersPOJOJs(String value) {
Gson gson = new Gson();
JsonReader reader = new JsonReader(new StringReader(value));
reader.setLenient(true);
UsersPOJO data = new UsersPOJO.User();
try {
data = gson.fromJson(reader,UsersPOJOr.class);
}catch ( JsonSyntaxException e){
e.printStackTrace();
}
return data;
}
kotlin
fun getUsersPOJO getOUsersPOJOListJs(value: String) : UsersPOJO {
val gson = Gson()
val reader = JsonReader(StringReader(value))
reader.isLenient = true
var data = UsersPOJO()
try {
data = gson.fromJson<Options>(reader, UsersPOJO::class.java)
}catch (e: JsonSyntaxException){
e.printStackTrace()
}
return data
}
5.in onResponse 改造请求回调块,如果你期望得到 json 数组 所以调用这个方法
java
public static List<UserPOJO> getUserPOJOList(String value) {
Gson gson = new Gson();
Type listType = new TypeToken<List<UserPOJO>>() {}.getType();
List<UserPOJO> data = new ArrayList<UserPOJO>();
try {
data =new ArrayList<UserPOJO>(gson.fromJson(value,listType));
}catch ( JsonSyntaxException e){
e.printStackTrace();
}
return data;
}
kotlin
fun getUserPOJOList(value: String) : List<UserPOJO>{
val gson = Gson()
val listType = object : TypeToken<List<UserPOJO>>() {}.type
var data = ArrayList<UserPOJO>()
try {
data = gson.fromJson<List<UserPOJO>>(value, listType) as ArrayList<UserPOJO>
}catch (e: JsonSyntaxException){
e.printStackTrace()
}
return data
}
我对 Retrofit 调用有疑问。我想获取一些数据,只是为了测试目的,看看是否有任何结果,但如您所见,没有任何结果。我得到类似 0、0.0、null 的数据。
Json 回应
{
"page": 1,
"total_results": 1295,
"total_pages": 65,
"results": [
{
"vote_count": 1669,
"id": 10515,
"video": false,
"vote_average": 8,
"title": "Castle in the Sky",
"popularity": 15.853,
"poster_path": "\/npOnzAbLh6VOIu3naU5QaEcTepo.jpg",
"original_language": "ja",
"original_title": "天空の城ラピュタ",
"genre_ids": [
12,
14,
16,
28,
10751,
10749
],
"backdrop_path": "\/fnMzL4G6HYilH1w1leFXOY5b29m.jpg",
"adult": false,
"overview": "A young boy and a girl with a magic crystal must race against pirates and foreign agents in a search for a legendary floating castle.",
"release_date": "1986-08-02"
},
{
"vote_count": 154,
"id": 487672,
"video": false,
"vote_average": 6.7,
"title": "Reign of the Supermen",
"popularity": 15.461,
"poster_path": "\/e9TzqscNRUaG8HqEP3K1jUvi8pC.jpg",
"original_language": "en",
"original_title": "Reign of the Supermen",
"genre_ids": [
16,
28,
878
],
"backdrop_path": "\/cdCMUHWyXBOsbLL4dOEPdCEtwM4.jpg",
"adult": false,
"overview": "In the wake of The Death of Superman, the world is still mourning the loss of the Man of Steel following his fatal battle with the monster Doomsday. However, no sooner as his body been laid to rest than do four new bearers of the Superman shield come forward to take on the mantle. The Last Son of Krypton, Superboy, Steel, and the Cyborg Superman all attempt to fill the vacuum left by the world's greatest champion. Meanwhile, Superman's death has also signaled to the universe that Earth is vulnerable. Can these new Supermen and the rest of the heroes prove them wrong?",
"release_date": "2019-01-13"
}
]
}
接口调用
@GET("3/discover/movie?api_key=APIKEY&with_genres=27")
Call<model> getABC();
改造调用
String url = "https://api.themoviedb.org/";
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build();
apiCall api = retrofit.create(apiCall.class);
Call<model> call = api.getABC();
call.enqueue(new Callback<model>() {
@Override
public void onResponse(Call<model> call, Response<model> response) {
if (!response.isSuccessful()){
}
List<model> list = Collections.singletonList(response.body());
for (model model : list) {
String content = "";
content += model.getVote_count() + "\n";
content += model.getVote_average() + "\n";
content += model.getOverview() + "\n\n\n";
System.out.println(content);
}
}
@Override
public void onFailure(Call<model> call, Throwable t) {
}
});
}
POJO
public class model {
@SerializedName("vote_count")
private int vote_count;
@SerializedName("vote_average")
private double vote_average;
@SerializedName("overview")
private String overview;
public int getVote_count() {
return vote_count;
}
public double getVote_average() {
return vote_average;
}
public String getOverview() {
return overview;
}
我应该在代码中更改什么?我会感激每一个提示。我从通话中收到的代码是 200 - 所以通话成功,我的 pojo class 有问题吗?
*已编辑 POJO
public class model {
@SerializedName("results")
@Expose
private List<movies> results;
public List<movies> getResults() {
return results;
}
class movies {
@SerializedName("vote_count")
@Expose
private Integer voteCount;
@SerializedName("vote_average")
@Expose
private Double voteAverage;
@SerializedName("overview")
@Expose
private String overview;
}
}
编辑改造电话
public void onResponse(Call<model> call, Response<model> response) {
if (!response.isSuccessful()){
}
List<model> list = Collections.singletonList(response.body());
for (model model : list) {
System.out.println(model.getResults());
}
}
这是我收到的部分。
com.example.x.model$movies@5f6763b,
com.example.x.model$movies@e988158,
com.example.x.model$movies@6812b1,
为什么没有正确命名?
您的模型 class 应如下所示:
public class Model {
@SerializedName("page")
private int page;
@SerializedName("results")
private List<Result> results;
@SerializedName("total_results")
private int total;
@SerializedName("total_pages")
private int totalPages;
//.......getter setter methods
}
public class Result{
@SerializedName("vote_count")
private int voteCount;
@SerializedName("vote_average")
private double voteAverage;
@SerializedName("overview")
private String overView;
//.....other fields
//......getter setter methods
}
那么改造调用应该是这样的:
Call<model> call = api.getABC();
call.enqueue(new Callback<Model>() {
@Override
public void onResponse(Call<Model> call, Response<Model> response) {
if (response.isSuccessful()) {
List<Result> results=response.body().getResults();
for(Result result:results){
Log.d(TAG,"Result: "+result.getVoteCount())
}
}
}
@Override
public void onFailure(Call<Model> call, Throwable t) {
}
});
编码愉快.... :)
使用 this 站点在 java
中生成正确的响应 class响应 class 将如下所示:
public class BasicResponse implements Serializable
{
@SerializedName("page")
@Expose
private long page;
@SerializedName("total_results")
@Expose
private long totalResults;
@SerializedName("total_pages")
@Expose
private long totalPages;
@SerializedName("results")
@Expose
private List<Result> results = null;
private final static long serialVersionUID = 8749582078961182468L;
public long getPage() {
return page;
}
public void setPage(long page) {
this.page = page;
}
public long getTotalResults() {
return totalResults;
}
public void setTotalResults(long totalResults) {
this.totalResults = totalResults;
}
public long getTotalPages() {
return totalPages;
}
public void setTotalPages(long totalPages) {
this.totalPages = totalPages;
}
public List<Result> getResults() {
return results;
}
public void setResults(List<Result> results) {
this.results = results;
}
}
//-----------------------------------com.example.Result.java--------------
package com.example;
import java.io.Serializable;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Result implements Serializable
{
@SerializedName("vote_count")
@Expose
private long voteCount;
@SerializedName("id")
@Expose
private long id;
@SerializedName("video")
@Expose
private boolean video;
@SerializedName("vote_average")
@Expose
private double voteAverage;
@SerializedName("title")
@Expose
private String title;
@SerializedName("popularity")
@Expose
private double popularity;
@SerializedName("poster_path")
@Expose
private String posterPath;
@SerializedName("original_language")
@Expose
private String originalLanguage;
@SerializedName("original_title")
@Expose
private String originalTitle;
@SerializedName("genre_ids")
@Expose
private List<Long> genreIds = null;
@SerializedName("backdrop_path")
@Expose
private String backdropPath;
@SerializedName("adult")
@Expose
private boolean adult;
@SerializedName("overview")
@Expose
private String overview;
@SerializedName("release_date")
@Expose
private String releaseDate;
private final static long serialVersionUID = 2770789699641812364L;
public long getVoteCount() {
return voteCount;
}
public void setVoteCount(long voteCount) {
this.voteCount = voteCount;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public boolean isVideo() {
return video;
}
public void setVideo(boolean video) {
this.video = video;
}
public double getVoteAverage() {
return voteAverage;
}
public void setVoteAverage(double voteAverage) {
this.voteAverage = voteAverage;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public double getPopularity() {
return popularity;
}
public void setPopularity(double popularity) {
this.popularity = popularity;
}
public String getPosterPath() {
return posterPath;
}
public void setPosterPath(String posterPath) {
this.posterPath = posterPath;
}
public String getOriginalLanguage() {
return originalLanguage;
}
public void setOriginalLanguage(String originalLanguage) {
this.originalLanguage = originalLanguage;
}
public String getOriginalTitle() {
return originalTitle;
}
public void setOriginalTitle(String originalTitle) {
this.originalTitle = originalTitle;
}
public List<Long> getGenreIds() {
return genreIds;
}
public void setGenreIds(List<Long> genreIds) {
this.genreIds = genreIds;
}
public String getBackdropPath() {
return backdropPath;
}
public void setBackdropPath(String backdropPath) {
this.backdropPath = backdropPath;
}
public boolean isAdult() {
return adult;
}
public void setAdult(boolean adult) {
this.adult = adult;
}
public String getOverview() {
return overview;
}
public void setOverview(String overview) {
this.overview = overview;
}
public String getReleaseDate() {
return releaseDate;
}
public void setReleaseDate(String releaseDate) {
this.releaseDate = releaseDate;
}
}
您应该检查的所有步骤:
- 在邮递员或每个浏览器中调用您的 api 以 get 和 检查 响应json
- 将您的 json 响应 (您预期的) 复制到 http://www.jsonschema2pojo.org/ 此站点以获取该站点的 POJO
- 在 base URL 和 endpoint 中阻止你的 api 地址并创建改造请求
- in onResponse 改造请求回调块,如果你期望得到 json Object 所以调用这个方法
java
public static UsersPOJO getOUsersPOJOJs(String value) {
Gson gson = new Gson();
JsonReader reader = new JsonReader(new StringReader(value));
reader.setLenient(true);
UsersPOJO data = new UsersPOJO.User();
try {
data = gson.fromJson(reader,UsersPOJOr.class);
}catch ( JsonSyntaxException e){
e.printStackTrace();
}
return data;
}
kotlin
fun getUsersPOJO getOUsersPOJOListJs(value: String) : UsersPOJO {
val gson = Gson()
val reader = JsonReader(StringReader(value))
reader.isLenient = true
var data = UsersPOJO()
try {
data = gson.fromJson<Options>(reader, UsersPOJO::class.java)
}catch (e: JsonSyntaxException){
e.printStackTrace()
}
return data
}
5.in onResponse 改造请求回调块,如果你期望得到 json 数组 所以调用这个方法
java
public static List<UserPOJO> getUserPOJOList(String value) {
Gson gson = new Gson();
Type listType = new TypeToken<List<UserPOJO>>() {}.getType();
List<UserPOJO> data = new ArrayList<UserPOJO>();
try {
data =new ArrayList<UserPOJO>(gson.fromJson(value,listType));
}catch ( JsonSyntaxException e){
e.printStackTrace();
}
return data;
}
kotlin
fun getUserPOJOList(value: String) : List<UserPOJO>{
val gson = Gson()
val listType = object : TypeToken<List<UserPOJO>>() {}.type
var data = ArrayList<UserPOJO>()
try {
data = gson.fromJson<List<UserPOJO>>(value, listType) as ArrayList<UserPOJO>
}catch (e: JsonSyntaxException){
e.printStackTrace()
}
return data
}