Last active
September 30, 2020 06:24
-
-
Save micadasystems/06f1ae709e7c79a3fbee3b4cf16a50ac to your computer and use it in GitHub Desktop.
Example using Kotlin and Moshi
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.squareup.moshi.JsonAdapter | |
import com.squareup.moshi.JsonReader | |
import com.squareup.moshi.Moshi | |
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory | |
class Person(val id: Int, val name: String) | |
fun main() { | |
val moshi: Moshi = Moshi.Builder() | |
.add(KotlinJsonAdapterFactory()) | |
.build() | |
val jsonAdapter: JsonAdapter<Person> = moshi.adapter<Person>(Person::class.java) | |
// convert from json string to object | |
val string = "{\"id\": 1, \"name\": \"August\"}" | |
val person = jsonAdapter.lenient().fromJson(string) | |
println("id=${person!!.id}, name=${person!!.name}") | |
// id=1, name=August | |
// convert from object to json string | |
val personJson = jsonAdapter.toJson(person) | |
println(personJson) | |
// {"id":1,"name":"August"} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment