elsonwx
elsonwx

Reputation: 1629

how kotlin serialize JSONObject or Map to string with sorted keys?

I want to serialize a JSONObject or a Map to string with sorted_keys.

val mapObject = mapOf<String, Any>(
    "b" to arrayOf(
        "bb",
        mapOf<String, Any>(
            "bbb" to "bbb",
            "aaa" to "aaa"
        ), 
        "aa"
    ),
    "a" to "a"
)
val jsonObject = JSONObject(mapObject)
println(jsonObject.toString())

It prints

{"b":["bb",{"bbb":"bbb","aaa":"aaa"},"aa"],"a":"a"}

but I want it prints

{"a": "a", "b": ["bb", {"aaa": "aaa", "bbb": "bbb"}, "aa"]}

In Python there is

json.dumps(jsonObject, sort_keys=True)

to do this.

In Swift there is

jsonObject.rawString(options: [.sortedKeys])

to do this

but there seems to be no elegant method to do this in Android Kotlin.

Upvotes: 0

Views: 486

Answers (1)

lase
lase

Reputation: 2634

JSONObject is primarily an unsafe & intermediary format, so there aren't a ton of options for working with it in that form, primarily favoring deserialization to "actual" class representations for any work.

To this end, if you have control over the input of your map, you could switch from using mapOf<String, Any> to sortedMapOf<String, Any> - Kotlin maintains distinct implementations for this (similarly, if you wanted to edit your map after construction, you'd want a mutableMapOf<String, Any>).

If you already have an existing map, you can also use the method toSortedMap.

By default, all ordering should be done based on the natural order of the keys.

Upvotes: 1

Related Questions