5
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

kotlinでJSONObjectを簡単作成

Last updated at Posted at 2020-08-08

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)
    }
}

5
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?