Kotlin解析数据(九)

xiaoxiao2021-02-28  156

第一、转换json到数据类。 我们现在知道怎么去创建一个数据类,那我们开始准备去解析数据。在date包中,创建一个名为ResponseClasses.kt新的文件,想必我们已经都熟悉了解Json数据的结构。它的基本组成包括一个城市,一个系列的天气预报,这个城市有id,名字,所在的坐标。每一个天气预报有很多信息,比如日期,不同的温度,和一个由描述和图标的id。 在我们当前的UI中,我们不会去使用所有的这些数据。我们会解析所有到类里面,因为可能会在以后某些情况下会用到。以下就是我们需要使用到的类: data class ForecastResult(val city: City, val list: List<Forecast>) data class City(val id: Long, val name: String, val coord: Coordinates, val country: String, val population: Int) data class Coordinates(val lon: Float, val lat: Float) data class Forecast(val dt: Long, val temp: Temperature, val pressure: Float, val humidity: Int, val weather: List<Weather>, val speed: Float, val deg: Int, val clouds: Int, val rain: Float) data class Temperature(val day: Float, val min: Float, val max: Float, val night: Float, val eve: Float, val morn: Float) data class Weather(val id: Long, val main: String, val description: String, val icon: String) 当我们使用Gson来解析json到我们的类中,这些属性的名字必须要与json中的名字一样,或者可以指定一个serialised name(序列化名称)。一个好的实践是,大部分的软件结构中会根据我们app中布局来解耦成不同的模型。所以我喜欢使用声明简化这些类,因为我会在app其它部分使用它之前解析这些类。属性名称与json结果中的名字是完全一样的。 现在,为了返回被解析后的结果,我们的Request类需要进行一些修改。它将仍然只接收一个城市的zipcode作为参数而不是一个完整的url,因此这样变得更加具有可读性。现在,我会把这个静态的url放在一个companion object(伴随对象)中。如果我们之后还要对该API增加更多请求,我们需要提取它。 这里顺便说一下Companion objects这个概念:Kotlin允许我们去定义一些行为与静态对象一样的对象。尽管这些对象可以用众所周知的模式来实现,比如容易实现的单例模式。我们需要一个类里面有一些静态的属性、常量或者函数,我们可以使用companion objecvt。这个对象被这个类的所有对象所共享,就像Java中的静态属性或者方法。 public class ForecastRequest(val zipCode: String) { companion object { private val APP_ID = "15646a06818f61f7b8d7823ca833e1ce" private val URL = "http://api.openweathermap.org/data/2.5/" + "forecast/daily?mode=json&units=metric&cnt=7" private val COMPLETE_URL = "$URL&APPID=$APP_ID&q=" } fun execute(): ForecastResult { val forecastJsonStr = URL(COMPLETE_URL + zipCode).readText() return Gson().fromJson(forecastJsonStr, ForecastResult::class.java) } } 记得在build.gradle中增加你需要的Gson依赖: compile "com.google.code.gson:gson:2.4"

第二、构建domain层 我们现在创建一个新的包作为domain层。这一层中会包含一些Commands的实现来为app执行任务。 首先,必须要定义一个Command: public interface Command<T> { fun execute(): T } 这个command会执行一个操作并且返回某种类型的对象,这个类型可以通过范型被指定。大家需要知道一个有趣的概念,一切kotlin函数都会返回一个值。如果没有指定,它就默认返回一个Unit类。所以如果我们想让Command不返回数据,我们可以指定它的类型为Unit。 Kotlin中的接口比Java(Java 8以前)中的强大多了,因为它们可以包含代码。 第一个command需要去请求天气预报结构然后转换结果为domain类。下面这些类会在domain类中被定义: data class ForecastList(val city: String, val country: String, val dailyForecast:List<Forecast>) data class Forecast(val date: String, val description: String, val high: Int, val low: Int) 当更多的功能被增加,这些类可能会需要在以后被审查。但是现在这些类对我们来说已经足够了。这些类必须从数据映射到我们的domain类,所以我接下来需要创建一个DataMapper: public class ForecastDataMapper { fun convertFromDataModel(forecast: ForecastResult): ForecastList { return ForecastList(forecast.city.name, forecast.city.country, convertForecastListToDomain(forecast.list)) private fun convertForecastListToDomain(list: List<Forecast>): List<ModelForecast> { return list.map { convertForecastItemToDomain(it) } } private fun convertForecastItemToDomain(forecast: Forecast): ModelForecast { return ModelForecast(convertDate(forecast.dt), forecast.weather[0].description, forecast.temp.max.toInt(), forecast.temp.min.toInt()) } private fun convertDate(date: Long): String { val df = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.getDefault()) return df.format(date * 1000) } } 当我们使用了两个相同名字的类,我们可以给其中一个指定一个别名,这样我们就不需要写完整的包名了:import com.antonioleiva.weatherapp.domain.model.Forecast as ModelForecast 这些代码中另一个有趣的是我们从一个forecast list中转换为domain model的方法: return list.map { convertForecastItemToDomain(it) } 这一条语句,我们就可以循环这个集合并且返回一个转换后的新的List。Kotlin在List中提供了很多不错的函数操作符,它们可以在这个List的每个item中应用这个操作并且任何方式转换它们。对比Java 7,这是Kotlin其中一个强大的功能。我们很快就会查看所有不同的操作符。知道它们的存在是很重要的,因为它们要方便得多,并可以节省很多时间和模版。 现在,编写命令前的准备就绪: class RequestForecastCommand(val zipCode: String) : Command<ForecastList> { override fun execute(): ForecastList { val forecastRequest = ForecastRequest(zipCode) return ForecastDataMapper().convertFromDataModel( forecastRequest.execute()) } } 第三、在UI中绘制数据 MainActivity中的代码有些小的改动,因为现在有真实的数据需要填充到adapter中。异步调用需要被重写成: async() { val result = RequestForecastCommand("94043").execute() uiThread{ forecastList.adapter = ForecastListAdapter(result) } } Adapter也需要被修改: class ForecastListAdapter(val weekForecast: ForecastList) : RecyclerView.Adapter<ForecastListAdapter.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder? { return ViewHolder(TextView(parent.getContext())) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { with(weekForecast.dailyForecast[position]) { holder.textView.text = "$date - $description - $high/$low" } } override fun getItemCount(): Int = weekForecast.dailyForecast.size class ViewHolder(val textView: TextView) : RecyclerView.ViewHolder(textView) } with函数 with是一个非常有用的函数,它包含在Kotlin的标准库中。它接收一个对象和一个扩展函数作为它的参数,然后使这个对象扩展这个函数。这表示所有我们在括号中编写的代码都是作为对象(第一个参数)的一个扩展函数,我们可以就像作为this一样使用所有它的public方法和属性。当我们针对同一个对象做很多操作的时候这个非常有利于简化代码。
转载请注明原文地址: https://www.6miu.com/read-21807.html

最新回复(0)