【问题标题】:How to get a value in JSON by an id value in the class in Kotlin如何通过 Kotlin 类中的 id 值获取 JSON 中的值
【发布时间】:2019-05-13 01:37:32
【问题描述】:

我想在我用城市的“名称”搜索的城市的“天气”数组中获取“温度”值。 我是用 f​​or 循环来做的,但速度很慢,还有其他更好的方法吗?

这是 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


【解决方案1】:

是的,您可以使用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()

希望对你有所帮助。

【讨论】:

    猜你喜欢
    • 2018-02-15
    • 2021-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多