首页 > 解决方案 > 我如何在 android 应用程序中模拟 REST 后端

问题描述

我的 android 应用程序通过 REST API 与后端服务通信。我想模拟出这个 API 来快速开发前端。我正在使用 android volley 作为客户端网络库..

标签: android

解决方案


我会将模拟数据作为 json 存储在我的资产文件夹中,并从这些 json 文件创建我的数据:

fun getJsonFromAssets(context: Context, jsonPath: String): String? {
    return try {
        context.assets.open(jsonPath).bufferedReader().use{
            it.readText()
        }
    } catch (e: IOException) {
        null
    }
}

然后得到像这样的对象(这里以列表为例):

val list = gson.fromJson<List<MyObject>>(jsonString, object : TypeToken<List<MyObject>>() {}.type)

推荐阅读