【发布时间】:2018-07-18 08:13:20
【问题描述】:
我想将对象(通过 Retrofit 获得)传递给片段。我听说过两种方法,但两种方法都有问题。我正在尝试将 FullForecast 对象传递给我的片段。
- 使用
Parcelize。我在课堂上实现了它,但它与我的构造函数冲突。
- 我听说我可以将 Json 字符串从活动传递到片段,然后在片段内将其转换为对象。但是,我无法从我的 Json 调用中获取 Json 字符串。我试过
Call<ResponseBody>,也试过response.body().toString(),但没有得到Json字符串
这是我的代码
repository.getWeatherForecast(place,
object : Callback<FullForecast> {
override fun onFailure(call: Call<FullForecast>?, t: Throwable?) {
println("onFailure")
}
override fun onResponse(call: Call<FullForecast>?, response: Response<FullForecast>?) {
if (response != null && response.isSuccessful && response.body() != null) {
forecastObj = response.body() as FullForecast
// Try to get Json string here
}
}
})
@JsonClass(generateAdapter = true)
data class FullForecast(@Json(name = "list")
val forecastList: List<WeatherForecast>) {
}
@JsonClass(generateAdapter = true)
data class WeatherForecast(@Json(name = "main")
val weatherDetail: WeatherDetail,
@Json(name = "weather")
val weatherIcon: List<WeatherIcon>,
@Json(name = "dt_txt")
val date: String) {
}
@JsonClass(generateAdapter = true)
data class Place(@Json(name = "main")
val weatherDetail: WeatherDetail,
@Json(name = "weather")
val weatherIcon: List<WeatherIcon>,
@Json(name = "sys")
val countryDetail: CountryDetail,
@Json(name = "dt_txt")
var forecastDate: String = "",
val name: String,
var placeIdentifier: String = "",
var lastUpdated: String = "") {
}
@JsonClass(generateAdapter = true)
data class CountryDetail(val country: String) {
}
@JsonClass(generateAdapter = true)
data class WeatherDetail(@Json(name = "temp")
val temperature: Double,
val temp_min: Double,
val temp_max: Double) {
}
@JsonClass(generateAdapter = true)
data class WeatherIcon(val icon: String) {
}
【问题讨论】:
-
你能提供完整的
FullForecast类吗? -
@GianhTran 完成。这实际上是整个班级
-
知道了,请在下面查看我的答案
标签: android json android-fragments parcelable