Created
September 30, 2020 11:08
-
-
Save micadasystems/b6f24bed2d7efe66283cc95f847ec4d9 to your computer and use it in GitHub Desktop.
Kotlin - moshi convert JSON string list to list of objects
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import com.github.kittinunf.fuel.httpGet | |
import com.github.kittinunf.result.Result | |
import com.squareup.moshi.JsonAdapter | |
import com.squareup.moshi.Moshi | |
import com.squareup.moshi.Types | |
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory | |
import java.lang.reflect.Type | |
class Post ( | |
val title: String = "", | |
val userId: Int = 0, | |
val id: Int = 0, | |
val body: String = "") { | |
override fun toString(): String { | |
return "id=${id} title=${title}" | |
} | |
} | |
fun main() { | |
val moshi: Moshi = Moshi.Builder() | |
.add(KotlinJsonAdapterFactory()) | |
.build() | |
val httpAsync = "https://jsonplaceholder.typicode.com/posts" | |
.httpGet() | |
.responseString { request, response, result -> | |
when (result) { | |
is Result.Failure -> { | |
val ex = result.getException() | |
println(ex) | |
} | |
is Result.Success -> { | |
val data = result.get() | |
println(data) | |
val type: Type = Types.newParameterizedType(List::class.java, Post::class.java) | |
val adapter: JsonAdapter<List<Post>> = moshi.adapter(type) | |
val posts: List<Post>? = adapter.fromJson(data) | |
for(post in posts!!) { | |
println(post) | |
} | |
} | |
} | |
} | |
httpAsync.join() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment