问题
i tried to parse json data, but it kind of weird because it not show the right data but if i tried to called json on browser it has the right data.
so this is how i parse the json data
doAsync {
val url = localhost.getMovie()
val request = okhttp3.Request.Builder().url(url).build()
val client = OkHttpClient()
uiThread {
client.newCall(request).enqueue(object : Callback, okhttp3.Callback {
override fun onResponse(call: okhttp3.Call?, response: okhttp3.Response?) {
val body = response?.body()?.string()
println(body)
uiThread {
val gson = GsonBuilder().create()
val movieFeed = gson.fromJson(body, Movie2Response::class.java)
Log.v("body", ""+body)
Log.v("feed", ""+movieFeed.data)
uiThread {
}
}
}
override fun onFailure(call: okhttp3.Call?, e: IOException) {
println("failed")
}
})
}
}
movie response
class Movie2Response (val data: MutableList<Movie2>)
movie
class Movie2 (
@SerializedName("id")
var movieId: String? = null,
@SerializedName("description")
var synopsis: String? = null,
@SerializedName("release_date")
var release: String? = null,
@SerializedName("poster")
var poster: String? = null,
@SerializedName("genre")
var genre: String? = null,
@SerializedName("title")
var title: String? = null
)
and this is what i got from the json data
V/body: {"data":[{"title":"Aquaman","description":""........
V/feed: [com.mqa.android.moviereview.model.Movie2@7509e04, com.mqa.android.moviereview.model.Movie2@890afed, com.mqa.android.moviereview.model.Movie2@9834e22, com.mqa.android.moviereview.model.Movie2@f02d0b3, com.mqa.android.moviereview.model.Movie2@d3b9670, com.mqa.android.moviereview.model.Movie2@4d55de9, com.mqa.android.moviereview.model.Movie2@cac2a6e, com.mqa.android.moviereview.model.Movie2@94fc50f, com.mqa.android.moviereview.model.Movie2@d9ba99c]
it shows right in body but in the array it show like that. please help what is wrong with it. because i want to show the title data to the spinner
回答1:
Your code worked pretty well as the log results showed. The real problem is the log function Log.v("feed", ""+movieFeed.data)
. If you want to show pretty log, you should override the toString()
method in Movie2
class by:
Open
Movie2
and right click in theeditor
->Generate
-> then clicktoString()
to override it.
For data class in Kotlin, you can just add data
before class
keyword.
回答2:
Everything okey with you data. You just forgot adding default realisation to log this object.
class Movie2(/*your fields*/)
just add data before class. will be something like that
data class Movie2(/*your fields*/)
Kotlin doesn't know ho toString you Movie2. If you wanna default realisation use data class
来源:https://stackoverflow.com/questions/54358667/how-to-parse-data-from-json