Json in Kotlin

import kotlinx.serialization.*
import kotlinx.serialization.json.*

// We'll use these two data classes to demonstrate encoding and
// decoding of custom types below.
@Serializable
data class Response1(
    val page: Int,
    val fruits: List<String>
)

// Fields must be declared as properties to be serialized/deserialized in JSON.
@Serializable
data class Response2(
    @SerialName("page") val pageNumber: Int,
    @SerialName("fruits") val fruitsList: List<String>
)

fun main() {
    // First we'll look at encoding basic data types to
    // JSON strings. Here are some examples for atomic values.
    val bolB = Json.encodeToString(true)
    println(bolB)

    val intB = Json.encodeToString(1)
    println(intB)

    val fltB = Json.encodeToString(2.34)
    println(fltB)

    val strB = Json.encodeToString("gopher")
    println(strB)

    // And here are some for lists and maps, which encode
    // to JSON arrays and objects as you'd expect.
    val slcD = listOf("apple", "peach", "pear")
    val slcB = Json.encodeToString(slcD)
    println(slcB)

    val mapD = mapOf("apple" to 5, "lettuce" to 7)
    val mapB = Json.encodeToString(mapD)
    println(mapB)

    // The JSON package can automatically encode your
    // custom data types.
    val res1D = Response1(1, listOf("apple", "peach", "pear"))
    val res1B = Json.encodeToString(res1D)
    println(res1B)

    // You can use annotations on data class properties
    // to customize the encoded JSON key names. Check the
    // definition of `Response2` above to see an example
    // of such annotations.
    val res2D = Response2(1, listOf("apple", "peach", "pear"))
    val res2B = Json.encodeToString(res2D)
    println(res2B)

    // Now let's look at decoding JSON data into Kotlin
    // values. Here's an example for a generic data
    // structure.
    val byt = """{"num":6.13,"strs":["a","b"]}"""

    // We need to provide a type where the JSON
    // package can put the decoded data. This
    // `Map<String, JsonElement>` will hold a map of strings
    // to arbitrary data types.
    val dat = Json.parseToJsonElement(byt).jsonObject

    println(dat)

    // In order to use the values in the decoded map,
    // we'll need to convert them to their appropriate type.
    // For example here we convert the value in `num` to
    // the expected `Double` type.
    val num = dat["num"]?.jsonPrimitive?.double
    println(num)

    // Accessing nested data requires a series of
    // conversions.
    val strs = dat["strs"]?.jsonArray
    val str1 = strs?.get(0)?.jsonPrimitive?.content
    println(str1)

    // We can also decode JSON into custom data types.
    // This has the advantages of adding additional
    // type-safety to our programs and eliminating the
    // need for type assertions when accessing the decoded
    // data.
    val str = """{"page": 1, "fruits": ["apple", "peach"]}"""
    val res = Json.decodeFromString<Response2>(str)
    println(res)
    println(res.fruitsList[0])

    // In the examples above we always used strings as
    // intermediates between the data and JSON representation.
    // We can also stream JSON encodings directly to Writers.
    val jsonWriter = Json.encodeToString(mapOf("apple" to 5, "lettuce" to 7))
    println(jsonWriter)
}

This Kotlin code demonstrates JSON encoding and decoding using the kotlinx.serialization library. It covers encoding of basic data types, custom classes, and decoding JSON into Kotlin objects. The structure and explanations are adapted to Kotlin’s syntax and conventions while maintaining the overall flow of the original Go example.

To run this code, you’ll need to add the kotlinx.serialization dependency to your project and apply the serialization plugin. The exact steps may vary depending on your build system (Gradle, Maven, etc.).

Remember to import the necessary kotlinx.serialization packages at the top of your file.

This example showcases Kotlin’s powerful serialization capabilities, including custom naming of JSON fields using annotations, and the ability to work with both strongly-typed objects and dynamic JSON structures.