kotlinでJSONObjectを簡単作成


kotlinで、変数から JSONObject を作成したかったのですが、 まずはオブジェクト作って〜とかputして〜とか面倒だったのでパーサーを作りました。
自分用ですが、忘れないように残しておきます。

パーサー作成

JsonObjectBuilder.kt
internal fun json(build: JsonObjectBuilder.() -> Unit): JSONObject {
    return JsonObjectBuilder().json(build)
}

internal class JsonObjectBuilder {
    private val deque: Deque<JSONObject> = ArrayDeque()

    fun json(build: JsonObjectBuilder.() -> Unit): JSONObject {
        deque.push(JSONObject())
        this.build()
        return deque.pop()
    }

    @Suppress("RECEIVER_NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS")
    infix fun <T> String.to(value: T) {
        deque.peek().put(this, value ?: JSONObject.NULL)
    }
}

使用例


fun parseSample() {

    // こんな感じでJSONObjectを作成できます
    val jsonObject = json {
        "str" to "hoge"
        "int" to 123
        "null" to null
    }

    // 文字列にしたい場合は、普通にtoString()
    val jsonString = jsonObject.toString();

    // ネストしたJSONObjectはこんな感じ
    val nestedJsonObject = json {
        "hoge" to "hoge"
        "nestObj" to json {
            "fuga" to "fuga"
        }
    }

    // JSONArrayが作りたい場合はputしていってください
    val jsonArray = JSONArray()
    val list = listOf(1, 2, 3)
    list.forEach {
        val jsonObject = json {
             "num" to it
        }
        jsonArray.put(jsonObject)
    }
}