如何通过Kotlin中的类中的id值获取JSON中的值

时间:2019-05-13 01:37:32

标签: android arrays json kotlin fetch

我想在我用城市的“名称”搜索的城市的“天气”数组中获取“温度”值。 我是通过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)

}

1 个答案:

答案 0 :(得分:0)

是的,您可以使用list.find{}查找名称不循环的城市。

在您的代码中,应该是这样。

val cities = gson.fromJson<List<Cities>>(body, object : TypeToken<List<Cities>>() {}.type)
val cityFounded = cities.find{ it.name == nameOfCity.text.toString() }
showsTemp.text = cityFounded?.weather?.temp.toString()

希望它会对您有所帮助。