【问题标题】:Convert HttpURLConnection String Response to Kotlin Objects without third party libraries在没有第三方库的情况下将 HttpURLConnection 字符串响应转换为 Kotlin 对象
【发布时间】: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
)

【问题讨论】:

  • 完全不清楚您的输入是什么。或者想要的输出。所以我们不知道必须做什么。我们如何提供建议?

标签: android kotlin


【解决方案1】:

好吧,如果您想避免使用 3rd 方库,您可以编写自己的 json 解析器,但我建议您不要这样做。为什么不利用已被广泛使用和测试的其他人的工作,而是尝试重新发明轮子?

需要注意的一点是,Gson 不太了解 kotlin 可空类型,所以Moshikotlinx.serialization 可能会更好地为您服务。

【讨论】:

    猜你喜欢
    • 2015-01-29
    • 2021-03-10
    • 2012-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-16
    相关资源
    最近更新 更多