【发布时间】:2021-06-14 13:44:16
【问题描述】:
GlobalScope.launch(Dispatchers.Main) {
val result = httpGet("https://jsonplaceholder.typicode.com/todos/?userId=1")
var gson = Gson()
val itemType = object : TypeToken<List<Todo>>() {}.type
val todoList = gson.fromJson<List<Todo>>(result, itemType)
insertData(todoList)
val todoRecyclerView = findViewById<RecyclerView>(R.id.recyclerView)
val adapter = TodoItemAdapter(todoList)
todoRecyclerView.adapter = adapter
todoRecyclerView.layoutManager = LinearLayoutManager(applicationContext, LinearLayoutManager.VERTICAL, false)
}
private suspend fun httpGet(myURL: String?): String =
withContext(Dispatchers.IO){
val inputStream: InputStream
val result:String
// create URL
val url:URL = URL(myURL)
// create HttpURLConnection
val conn:HttpURLConnection = url.openConnection() as HttpURLConnection
// make GET request to the given URL
conn.connect()
// receive response as inputStream
inputStream = conn.inputStream
// convert inputstream to string
result = inputStream?.bufferedReader().use { it?.readText() } ?: "Did not work!"
result
}
我正在使用上面的代码连接到 API 并检索一些数据并将其转换为 kotlin 对象。我目前正在使用 Gson 进行转换。除了使用第三方库之外,还有其他方法吗?
来自 API 的响应。
[ { “用户ID”:1, “身份证”:1, "title": "delectus aut autem", “完成”:假 }, { “用户ID”:1, “身份证”:2, "title": "quis ut nam facilis et officia qui", “完成”:假 }, { “用户ID”:1, “身份证”:3, "title": "fugiat veniam minus", “完成”:假 }, { “用户ID”:1, “身份证”:4, "title": "et porro tempora", “完成”:真 } ]
Kotlin 对象:
@Entity(tableName = "todo")
data class Todo(
@PrimaryKey(autoGenerate = true)
val localId: Long = 0L,
@SerializedName("userId")
val userId: Long = 0L,
@SerializedName("id")val id: Long = 0L,
@SerializedName("title")val title: String = "",
@SerializedName("completed")val completed: Boolean = false
)
【问题讨论】:
-
完全不清楚您的输入是什么。或者想要的输出。所以我们不知道必须做什么。我们如何提供建议?