我正在使用Retrofit 2向TMDB发出API请求。我可以从日志中看到,请求正在发出,响应正在返回,但是,我的模型对象没有被填充。我已经仔细检查了JSON数据类型,很高兴它们没问题。有人能看出我做错了什么吗?
MovieListViewModel
@HiltViewModel
class MovieListViewModel @Inject constructor(private val repository: MoviesListRepository) : ViewModel() {
init {
viewModelScope.launch(Dispatchers.IO) {
val discoverMoviesResponse = getMovieList()
movieDataState.value = discoverMoviesResponse?.results ?: arrayListOf()
}
}
val movieDataState: MutableState<List<MovieData>> = mutableStateOf(emptyList())
private suspend fun getMovieList(): DiscoverMoviesResponse? {
return repository.getDiscoverMovies()
}
}
字符串
MoviesListRespository
class MoviesListRepository(private val tmdbWebService: TMDBWebService = TMDBWebService()) {
private var cachedDiscoverMoviesResponse:DiscoverMoviesResponse = DiscoverMoviesResponse(
0,
arrayListOf(),
0,
0
)
suspend fun getDiscoverMovies(): DiscoverMoviesResponse {
val response = tmdbWebService.getDiscoverMovies().discoverMoviesResponse
cachedDiscoverMoviesResponse = response
return response
}
}
型
TMDBWebService
class TMDBWebService {
private lateinit var api: TMDBApi
private val BASE_URL: String = "https://api.themoviedb.org/3/"
init {
val interceptor = HttpLoggingInterceptor()
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY)
val okHttpClient: OkHttpClient = OkHttpClient.Builder()
.addInterceptor(interceptor)
.build()
val retrofit = Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(okHttpClient)
.build()
api = retrofit.create(TMDBApi::class.java)
}
suspend fun getDiscoverMovies(): TMDBDiscoverMoviesResponse {
//ToDo: These should be passed in from a higher layer
return api.getDiscoverMovies(
API_KEY,
(VAL_COMPANIES_DISNEY_ANIMATION + PIPE_SEPARATOR + VAL_COMPANIES_DISNEY_PRODUCTION),
VAL_GENRES_ANIMATED
)
}
interface TMDBApi {
@GET("discover/movie")
suspend fun getDiscoverMovies(
@Query(PARAM_QUERY_API_KEY) apiKey: String,
@Query(PARAM_QUERY_KEY_WITH_COMPANIES) withCompany: String,
@Query(PARAM_QUERY_KEY_WITH_GENRES) withGenres: String
): TMDBDiscoverMoviesResponse
}
companion object {
private const val PIPE_SEPARATOR: String = "|"
private const val API_KEY: String = "ABC12345" //This is modified purely for sharing, the actual key is sent
private const val SEARCH_TYPE: String = "discover"
private const val PARAM_QUERY_API_KEY: String = "api_key"
private const val PARAM_QUERY_KEY_WITH_COMPANIES: String = "with_companies"
private const val PARAM_QUERY_KEY_WITH_GENRES: String = "with_genres"
private const val VAL_COMPANIES_DISNEY_ANIMATION: String = "6125"
private const val VAL_COMPANIES_DISNEY_PRODUCTION: String = "3166"
private const val VAL_GENRES_ANIMATED: String = "16"
}
}
型
TMDBApiResponse类
data class TMDBDiscoverMoviesResponse(val discoverMoviesResponse: DiscoverMoviesResponse)
data class DiscoverMoviesResponse(
@SerializedName("page") val page: Int,
@SerializedName("results") val results: List<MovieData>?,
@SerializedName("total_pages") val total_pages: Int,
@SerializedName("total_results") val total_results: Int,
)
data class MovieData(
@SerializedName("adult") val adult: Boolean,
@SerializedName("backdrop_path") val backdropPath: String,
@SerializedName("genre_ids") val genreIds: List<Int>,
@SerializedName("id") val id: Int,
@SerializedName("original_language") val originalLanguage: String,
@SerializedName("original_title") val originalTitle: String,
@SerializedName("overview") val overView: String,
@SerializedName("popularity") val popularity: Double,
@SerializedName("poster_path") val posterPath: String,
@SerializedName("release_date") val releaseDate: String,
@SerializedName("title") val title: String,
@SerializedName("video") val video: Boolean,
@SerializedName("vote_average") val voteAverage: Double,
@SerializedName("vote_count") val voteCount: Int
)
型
JSON响应
{"page":1,"results":[{"adult":false,"backdrop_path":"/3G1Q5xF40HkUBJXxt2DQgQzKTp5.jpg","genre_ids":[16,35,10751,14],"id":568124,"original_language":"en","original_title":"Encanto","overview":"The tale of an extraordinary family, the Madrigals, who live hidden in the mountains of Colombia, in a magical house, in a vibrant town, in a wondrous, charmed place called an Encanto. The magic of the Encanto has blessed every child in the family—every child except one, Mirabel. But when she discovers that the magic surrounding the Encanto is in danger, Mirabel decides that she, the only ordinary Madrigal, might just be her exceptional family's last hope.","popularity":301.126,"poster_path":"/4j0PNHkMr5ax3IA8tjtxcmPU3QT.jpg","release_date":"2021-10-13","title":"Encanto","video":false,"vote_average":7.6,"vote_count":8381},{"adult":false,"backdrop_path":"/f1xAxP0DFRGYSew9U8fhilP5itx.jpg","genre_ids":[16,35,10751],"id":1267,"original_language":"en","original_title":"Meet the Robinsons","overview":"Lewis, a brilliant young inventor, is keen on creating a time machine to find his mother, who abandoned him in an orphanage. Things take a turn when he meets Wilbur Robinson and his family.","popularity":151.961,"poster_path":"/naya0zF4kT401Sx15AtwB9vpcJr.jpg","release_date":"2007-03-23","title":"Meet the Robinsons","video":false,"vote_average":6.9,"vote_count":2512},{"adult":false,"backdrop_path":"/aRVQ1EgTx3vbhK6qls2O834bPQc.jpg","genre_ids":[16,10751],"id":11360,"original_language":"en","original_title":"Dumbo","overview":"Dumbo is a baby elephant born with over-sized ears and a supreme lack of confidence. But thanks to his even more diminutive buddy Timothy the Mouse, the pint-sized pachyderm learns to surmount all obstacles.","popularity":126.984,"poster_path":"/4x9FmvdJ464Fg7A9XcbYSmxfVw3.jpg","release_date":"1941-10-31","title":"Dumbo","video":false,"vote_average":7,"vote_count":4508},{"adult":false,"backdrop_path":"/cWczNud8Y8i8ab0Z4bxos4myWYO.jpg","genre_ids":[16,10751],"id":38757,"original_language":"en","original_title":"Tangled","overview":"When the kingdom's most wanted-and most charming-bandit Flynn Rider hides out in a mysterious tower, he's taken hostage by Rapunzel, a beautiful and feisty tower-bound teen with 70 feet of magical, golden hair. Flynn's curious captor, who's looking for her ticket out of the tower where she's been locked away for years, strikes a deal with the handsome thief and the unlikely duo sets off on an action-packed escapade, complete with a super-cop horse, an over-protective chameleon and a gruff gang of pub thugs.","popularity":117.62,"poster_path":"/ym7Kst6a4uodryxqbGOxmewF235.jpg","release_date":"2010-11-24","title":"Tangled","video":false,"vote_average":7.6,"vote_count":10371},{"adult":false,"backdrop_path":"/5tub2Kw6NboWFblA1CgDEwB59jP.jpg","genre_ids":[12,10751,16,28,35],"id":177572,"original_language":"en","original_title":"Big Hero 6","overview":"A special bond develops between plus-sized inflatable robot Baymax, and prodigy Hiro Hamada, who team up with a group of friends to form a band of high-tech heroes.","popularity":107.902,"poster_path":"/2mxS4wUimwlLmI1xp6QW6NSU361.jpg","release_date":"2014-10-24","title":"Big Hero 6","video":false,"vote_average":7.7,"vote_count":14556},{"adult":false,"backdrop_path":"/wQraxOsaq0NwTO9rSwLo4Nc8hVG.jpg","genre_ids":[10751,14,16,10749],"id":11224,"original_language":"en","original_title":"Cinderella","overview":"Cinderella has faith her dreams of a better life will come true. With help from her loyal mice friends and a wave of her Fairy Godmother's wand, Cinderella's rags are magically turned into a glorious gown and off she goes to the Royal Ball. But when the clock strikes midnight, the spell is broken, leaving a single glass slipper... the only key to the ultimate fairy-tale ending!","popularity":105.484,"poster_path":"/avz6S9HYWs4O8Oe4PenBFNX4uDi.jpg","release_date":"1950-02-22","title":"Cinderella","video":false,"vote_average":7,"vote_count":6134},{"adult
":false,"backdrop_path":"/n3pJwYuPnkw7JX7tOMbH0GRfBPn.jpg","genre_ids":[14,16,10751],"id":408,"original_language":"en","original_title":"Snow White and the Seven Dwarfs","overview":"A beautiful girl, Snow White, takes refuge in the forest in the house of seven dwarfs to hide from her stepmother, the wicked Queen. The Queen is jealous because she wants to be known as \"the fairest in the land,\" and Snow White's beauty surpasses her own.","popularity":98.42,"poster_path":"/v17k3Pwv1OEC4chJK49NOHqkbf8.jpg","release_date":"1937-12-21","title":"Snow White and the Seven Dwarfs","video":false,"vote_average":7.1,"vote_count":6733},{"adult":false,"backdrop_path":"/rcUcYzGGicDvhDs58uM44tJKB9F.jpg","genre_ids":[16,10751,14,28,12],"id":527774,"original_language":"en","original_title":"Raya and the Last Dragon","overview":"Long ago, in the fantasy world of Kumandra, humans and dragons lived together in harmony. But when an evil force threatened the land, the dragons sacrificed themselves to save humanity. Now, 500 years later, that same evil has returned and it’s up to a lone warrior, Raya, to track down the legendary last dragon to restore the fractured land and its divided people.","popularity":97.891,"poster_path":"/lPsD10PP4rgUGiGR4CCXA6iY0QQ.jpg","release_date":"2021-03-03","title":"Raya and the Last Dragon","video":false,"vote_average":7.9,"vote_count":6129},{"adult":false,"backdrop_path":"/z62CBlBBBOoNUuuxZ1jMAcq5ARE.jpg","genre_ids":[10749,10751,16],"id":10198,"original_language":"en","original_title":"The Princess and the Frog","overview":"A waitress, desperate to fulfill her dreams as a restaurant owner, is set on a journey to turn a frog prince back into a human being, but she has to face the same problem after she kisses him.","popularity":93.23,"poster_path":"/yprv5PbnEksoVj2v6XEnDBg9joR.jpg","release_date":"2009-12-08","title":"The Princess and the Frog","video":false,"vote_average":7.2,"vote_count":4970},{"adult":false,"backdrop_path":"/fydUcbkqLyESCFa9U5XKqi8dIVj.jpg","genre_ids":[16,10751,12,14],"id":109445,"original_language":"en","original_title":"Frozen","overview":"Young princess Anna of Arendelle dreams about finding true love at her sister Elsa’s coronation. Fate takes her on a dangerous journey in an attempt to end the eternal winter that has fallen over the kingdom. She's accompanied by ice delivery man Kristoff, his reindeer Sven, and snowman Olaf. On an adventure where she will find out what friendship, courage, family, and true love really means.","popularity":102.723,"poster_path":"/kgwjIb2JDHRhNk13lmSxiClFjVk.jpg","release_date":"2013-11-20","title":"Frozen","video":false,"vote_average":7.2,"vote_count":15313},{"adult":false,"backdrop_path":"/xJWPZIYOEFIjZpBL7SVBGnzRYXp.jpg","genre_ids":[10751,16,12,35,14],"id":330457,"original_language":"en","original_title":"Frozen II","overview":"Elsa, Anna, Kristoff and Olaf head far into the forest to learn the truth about an ancient mystery of their kingdom.","popularity":88.998,"poster_path":"/mINJaa34MtknCYl5AjtNJzWj8cD.jpg","release_date":"2019-11-20","title":"Frozen II","video":false,"vote_average":7.3,"vote_count":8945},{"adult":false,"backdrop_path":"/hWbNlp9Qq9DdnHNxn2WlVpGbSfI.jpg","genre_ids":[16,10751,14,12],"id":12092,"original_language":"en","original_title":"Alice in Wonderland","overview":"On a golden afternoon, young Alice follows a White Rabbit, who disappears down a nearby rabbit hole. Quickly following him, she tumbles into the burrow - and enters the merry, topsy-turvy world of Wonderland! Memorable songs and whimsical escapades highlight Alice's journey, which culminates in a madcap encounter with the Queen of Hearts - and her army of playing cards!","popularity":84.747,"poster_path":"/20cvfwfaFqNbe9Fc3VEHJuPRxmn.jpg","release_date":"1951-07-28","title":"Alice in Wonderland","video":false,"vote_average":7.2,"vote_count":5376},{"adult":false,"backdrop_path":"/p2fRZzxla6NoRbIH2KOZq0gHb5S.jpg","genre_ids":[16,12,10751,35],"id":269149,"original_language"
:"en","original_title":"Zootopia","overview":"Determined to prove herself, Officer Judy Hopps, the first bunny on Zootopia's police force, jumps at the chance to crack her first case - even if it means partnering with scam-artist fox Nick Wilde to solve the mystery.","popularity":89.82,"poster_path":"/hlK0e0wAQ3VLuJcsfIYPvb4JVud.jpg","release_date":"2016-02-11","title":"Zootopia","video":false,"vote_average":7.7,"vote_count":15028},{"adult":false,"backdrop_path":"/5wDBVictj4wUYZ31gR5WzCM9dLD.jpg","genre_ids":[16,10751,12,878],"id":877269,"original_language":"en","original_title":"Strange World","overview":"A journey deep into an uncharted and treacherous land, where fantastical creatures await the legendary Clades—a family of explorers whose differences threaten to topple their latest, and by far most crucial, mission.","popularity":65,"poster_path":"/fHMqfsYyl3lskPK2RiFRwhzwuep.jpg","release_date":"2022-11-23","title":"Strange World","video":false,"vote_average":6.5,"vote_count":1004},{"adult":false,"backdrop_path":"/ziC23LkMYj8gToQQYQGWSGJCLNF.jpg","genre_ids":[10751,16,35,12],"id":82690,"original_language":"en","original_title":"Wreck-It Ralph","overview":"Wreck-It Ralph is the 9-foot-tall, 643-pound villain of an arcade video game named Fix-It Felix Jr., in which the game's titular hero fixes buildings that Ralph destroys. Wanting to prove he can be a good guy and not just a villain, Ralph escapes his game and lands in Hero's Duty, a first-person shooter where he helps the game's hero battle against alien invaders. He later enters Sugar Rush, a kart racing game set on tracks made of candies, cookies and other sweets. There, Ralph meets Vanellope von Schweetz who has learned that her game is faced with a dire threat that could affect the entire arcade, and one that Ralph may have inadvertently started.","popularity":64.61,"poster_path":"/zWoIgZ7mgmPkaZjG0102BSKFIqQ.jpg","release_date":"2012-11-01","title":"Wreck-It Ralph","video":false,"vote_average":7.3,"vote_count":11400},{"adult":false,"backdrop_path":"/iBgPB2PVcFDwvUORdjnbHWqqTSF.jpg","genre_ids":[14,16,10749,10751],"id":10882,"original_language":"en","original_title":"Sleeping Beauty","overview":"A beautiful princess born in a faraway kingdom is destined by a terrible curse to prick her finger on the spindle of a spinning wheel and fall into a deep sleep that can only be awakened by true love's first kiss. Determined to protect her, her parents ask three fairies to raise her in hiding. But the evil Maleficent is just as determined to seal the princess's fate.","popularity":75.799,"poster_path":"/e3K5cLvVRXVxhw4mXQET92p1dnz.jpg","release_date":"1959-02-17","title":"Sleeping Beauty","video":false,"vote_average":6.9,"vote_count":4718},{"adult":false,"backdrop_path":"/qDQEQbgP3v7B9IYLAUcYexNrVYP.jpg","genre_ids":[10751,16,35,12],"id":404368,"original_language":"en","original_title":"Ralph Breaks the Internet","overview":"Video game bad guy Ralph and fellow misfit Vanellope von Schweetz must risk it all by traveling to the World Wide Web in search of a replacement part to save Vanellope's video game, Sugar Rush. In way over their heads, Ralph and Vanellope rely on the citizens of the internet — the netizens — to help navigate their way, including an entrepreneur named Yesss, who is the head algorithm and the heart and soul of trend-making site BuzzzTube.","popularity":63.915,"poster_path":"/iVCrhBcpDaHGvv7CLYbK6PuXZo1.jpg","release_date":"2018-11-20","title":"Ralph Breaks the Internet","video":false,"vote_average":7.2,"vote_count":6873},{"adult":false,"backdrop_path":"/vlLW4BPPS6XL8mxAvoJSppJV3Sv.jpg","genre_ids":[12,16,35,10751],"id":12230,"original_language":"en","original_title":"One Hundred and One Dalmatians","overview":"When a litter of dalmatian puppies are abducted by the minions of Cruella De Vil, the parents must find them before she uses them for a diabolical fashion statement.\r In a Disney animation classic, Dalmatian Pongo is tired of his bachelor-dog life. He
spies lovely Perdita and maneuvers his master, Roger, into meeting Perdita's owner, Anita. The owners fall in love and marry, keeping Pongo and Perdita together too. After Perdita gives birth to a litter of 15 puppies, Anita's old school friend Cruella De Vil wants to buy them all. Roger declines her offer, so Cruella hires the criminal Badun brothers to steal them -- so she can have a fur coat.","popularity":64.676,"poster_path":"/mRY84MJeWKnp9joev82QtslJFvk.jpg","release_date":"1961-01-25","title":"One Hundred and One Dalmatians","video":false,"vote_average":7.2,"vote_count":5717},{"adult":false,"backdrop_path":"/kZTfsQyZ1LJmuFp5bIHrXJxi5tl.jpg","genre_ids":[10751,16,12],"id":9325,"original_language":"en","original_title":"The Jungle Book","overview":"The boy Mowgli makes his way to the man-village with Bagheera, the wise panther. Along the way he meets jazzy King Louie, the hypnotic snake Kaa and the lovable, happy-go-lucky bear Baloo, who teaches Mowgli \"The Bare Necessities\" of life and the true meaning of friendship.","popularity":66.09,"poster_path":"/yN1kuupnPTLUprgfvC5WapgrxG4.jpg","release_date":"1967-10-18","title":"The Jungle Book","video":false,"vote_average":7.3,"vote_count":5725},{"adult":false,"backdrop_path":"/yGgEg4yimYQJLZrZg3Qhogp2raQ.jpg","genre_ids":[10751,16,10749],"id":10340,"original_language":"en","original_title":"Lady and the Tramp","overview":"Lady, a golden cocker spaniel, meets up with a mongrel dog who calls himself the Tramp. He is obviously from the wrong side of town, but happenings at Lady's home make her decide to travel with him for a while.","popularity":55.784,"poster_path":"/r9FiDSdBwNHdRwN0NMRrqfEHJGO.jpg","release_date":"1955-06-22","title":"Lady and the Tramp","video":false,"vote_average":7.1,"vote_count":4812}],"total_pages":37,"total_results":737}
型
JSON响应体
有人能看出我做错了什么吗?我没有看到任何错误,只是在签入代码时的响应体从未被填充,即。total_results等...总是0。
值得注意的是,MoviesListRepository
中的方法getDiscoverMovies
中的以下行返回null,即使OKHTTP日志指示已返回响应。val response = tmdbWebService.getDiscoverMovies().discoverMoviesResponse
个
1条答案
按热度按时间izkcnapc1#
不存在键为discoverMoviesResponse的JSON值,因此无法将JSON转换为
TMDBDiscoverMoviesResponse
。您需要将
TMDBApi
的getDiscoverMovies
的返回类型更改为DiscoverMoviesResponse
。