【发布时间】:2020-05-06 18:53:52
【问题描述】:
我想在 Kotlin 中将 json 用于天气应用程序,特别是用于预测,我想将预测显示为列表...
我有这个来自 json 的数据类
data class X(
val clouds: Clouds,
val dt: Int,
@SerializedName("dt_txt")
val dtTxt: String,
val main: Main,
val snow: Snow,
val sys: Sys,
val weather: List<Weather>,
val wind: Wind
)
这是我的服务
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.GET
private const val API_KEY = "de557725bd9504e26ff45267e4c3d806"
interface ForcastServices{
@GET("forecast")
fun getWeatherList(
@retrofit2.http.Query("lat") lat :Double,
@retrofit2.http.Query("lon") lon :Double
): Deferred<List<Weather>>
companion object{
operator fun invoke() :ForcastServices{
val requestInterceptor = Interceptor{chain ->
val url =chain.request()
.url()
.newBuilder()
.addQueryParameter("APPID", API_KEY)
.build()
val request =chain.request()
.newBuilder()
.url(url)
.build()
return@Interceptor chain.proceed(request)
}
val okHttpClient = OkHttpClient.Builder()
.addInterceptor(requestInterceptor)
.build()
return Retrofit.Builder()
.client(okHttpClient)
.baseUrl("http://api.openweathermap.org/data/2.5/forecast?")
.addCallAdapterFactory(CoroutineCallAdapterFactory())
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(ForcastServices::class.java)
}
}
}
这是我的 recyclerview 适配器
class RecyclerAdapterForcast(val weaTher: List<Weather>) :
RecyclerView.Adapter<ForcastViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ForcastViewHolder {
val fView =
LayoutInflater.from(parent.context).inflate(R.layout.list_forcast, parent, false)
return ForcastViewHolder(fView)
}
override fun getItemCount(): Int {
return weaTher.size
//return 8
}
override fun onBindViewHolder(holder: ForcastViewHolder, position: Int) {
val weaTher = weaTher.get(position)
holder.v.tex_test.text = weaTher.main
}
}
这是我的 MainActivity
@SuppressLint("SetTextI18n")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val apiServices = ForcastServices()
rec_forcast.layoutManager = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL ,false)
GlobalScope.launch(Dispatchers.Main) {
val currentForcastResponse = apiServices.getWeatherList(35.69,51.39).await()
val weatherlist = currentForcastResponse
rec_forcast.adapter = RecyclerAdapterForcast(weatherlist)
}
但它有一些错误.. 这些是我在项目中看到的一些错误 有时会在当天预报中返回 有时会出现此错误 java.lang.IllegalStateException:应为 BEGIN_ARRAY,但在第 1 行第 2 列路径 $
处为 BEGIN_OBJECT任何人都有这个问题的解决方案...
【问题讨论】:
标签: android json kotlin arraylist retrofit2