【发布时间】:2019-05-13 01:37:32
【问题描述】:
我想在我用城市的“名称”搜索的城市的“天气”数组中获取“温度”值。 我是用 for 循环来做的,但速度很慢,还有其他更好的方法吗?
这是 JSON 文件:https://ws.smn.gob.ar/map_items/weather
到目前为止,这是我的代码:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
fun fetchJson(view:View){
println("attemting to fetch JSON")
val url = "https://ws.smn.gob.ar/map_items/weather"
val request = Request.Builder().url(url).build()
val client = OkHttpClient()
client.newCall(request).enqueue(object: Callback {
override fun onResponse(call: Call, response: Response) {
var body = response?.body()?.string()
println(body)
val gson = GsonBuilder().create()
val cities = gson.fromJson<List<Cities>>(body, object : TypeToken<List<Cities>>() {}.type)
for(city in cities){
if(city.name.equals(nameOfCity.text.toString())){
showsTemp.text = city.weather.temp.toString()
}}
}
override fun onFailure(call: Call, e: IOException) {
println("Se fallo en establecer la comunicacion")
}
})
}
class Cities(val _id:String,
val name:String,
val province:String,
val weather: Weather)
class Weather(val humidity: Int,val temp: Double)
}
【问题讨论】:
-
你为什么不试试
Klaxon?我认为它比GSON快
标签: android arrays json kotlin fetch