以下示例代码来自网页,您能告诉我代码val jsonObj = json as JsonObject
的含义吗? Kotlin的关键字是as
吗?
谢谢!
open class WeatherDeserializer : JsonDeserializer<WeatherObject> {
override fun deserialize(json: JsonElement?, typeOfT: Type?, context: JsonDeserializationContext?): WeatherObject? {
val jsonObj = json as JsonObject
val wheather = WeatherObject()
val wind = WindObject()
val jsonWeatherArray = jsonObj.getAsJsonArray("weather").get(0)
val jsonMainObj = jsonObj.getAsJsonObject("main")
val jsonWindObj = jsonObj.getAsJsonObject("wind")
wheather.main = jsonWeatherArray.asJsonObject.get("main").asString
wheather.description = jsonWeatherArray.asJsonObject.get("description").asString
wheather.temp = jsonMainObj.get("temp").asFloat
wheather.tempMax = jsonMainObj.get("temp_max").asFloat
wheather.tempMin = jsonMainObj.get("temp_min").asFloat
wheather.humidity = jsonMainObj.get("humidity").asInt
wind.speed = jsonWindObj.get("speed").asFloat
wind.deg = jsonWindObj.get("deg").asFloat
wheather.wind = wind
return wheather
}
}
答案 0 :(得分:2)
答案 1 :(得分:1)
as
是一个类型转换操作符。
所以这只会将您json
JsonElement
的{{1}}对象投放到JsonObject
。
就像Java等同于JsonObject jsonObject = (JsonObject) json;
如需更多阅读此https://kotlinlang.org/docs/reference/typecasts.html#unsafe-cast-operator