Answers for "kotlin parse json"

2

kotlin parse json array

val jsonString = """
    {
       "type":"Foo",
       "data":[
          {
             "id":1,
             "title":"Hello"
          },
          {
             "id":2,
             "title":"World"
          }
       ]
    }        
"""
///////////////////////////////////////////////////
import org.json.JSONObject

class Response(json: String) : JSONObject(json) {
    val type: String? = this.optString("type")
    val data = this.optJSONArray("data")
            ?.let { 0.until(it.length()).map { i -> it.optJSONObject(i) } } // returns an array of JSONObject
            ?.map { Foo(it.toString()) } // transforms each JSONObject of the array into Foo
}

class Foo(json: String) : JSONObject(json) {
    val id = this.optInt("id")
    val title: String? = this.optString("title")
}
val foos = Response(jsonString)
Posted by: Guest on July-17-2021
1

kotlin json

import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json

@Serializable
class MyJsonClass(val name: String, val optionalInt: Int = 5)

fun main() {
  val jsonToEncode = MyJsonClass( "Alice", 10 )
  val encodedJson  = Json.encodeToString( jsonToEncode )
  val decodedJson  = Json.decodeFromString<MyJsonClass>( jsonString )
}
Posted by: Guest on January-30-2021

Browse Popular Code Answers by Language