Reputation: 275
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
}
I am using the above code to connect to an API and retrieve some data and convert it to a kotlin objects. I am using Gson currently for the conversion. Is there any other way rather than using third party libraries to do the same.
Response from the API.
[ { "userId": 1, "id": 1, "title": "delectus aut autem", "completed": false }, { "userId": 1, "id": 2, "title": "quis ut nam facilis et officia qui", "completed": false }, { "userId": 1, "id": 3, "title": "fugiat veniam minus", "completed": false }, { "userId": 1, "id": 4, "title": "et porro tempora", "completed": true } ]
Kotlin Object:
@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
)
Upvotes: 1
Views: 516
Reputation: 1958
Well, if you want to avoid 3rd party libraries, you can write your own json parser, but I would advise against it. Why not leverage work of others, that is widely used and tested and instead try and reinvent the wheel?
One thing to note is that Gson does not understand kotlin nullable types well, so maybe Moshi or kotlinx.serialization would serve you better.
Upvotes: 1