You can use org.json which is shipped with Android:
JSONObject(map).toString()
Answer from Miha_x64 on Stack OverflowYou can use org.json which is shipped with Android:
JSONObject(map).toString()
You can use Gson for that,
Here is the example,
val map = HashMap<String, String>()
map.put("key1","value1");
map.put("key2","value2");
map.put("key3","value3");
val gson = Gson()
Log.d("TAG", gson.toJson(map).toString())
and the oputput is,
{"key1":"value1","key2":"value2","key3":"value3"}
How to map a JSON string to Kotlin Map - Stack Overflow
Turning JSON array into Map
java - Kotlin: Cannot convert Map to JSON - Stack Overflow
map to json string error
How to pass JSON in Kotlin?
How to get value from JSON in Kotlin?
How to convert JSON to object in Kotlin?
No additional library is needed:
val jsonObj = JSONObject(jsonString)
val map = jsonObj.toMap()
where toMap is:
fun JSONObject.toMap(): Map<String, *> = keys().asSequence().associateWith {
when (val value = this[it])
{
is JSONArray ->
{
val map = (0 until value.length()).associate { Pair(it.toString(), value[it]) }
JSONObject(map).toMap().values.toList()
}
is JSONObject -> value.toMap()
JSONObject.NULL -> null
else -> value
}
}
This can be done with Klaxon. With this you can easily read the Json data as JsonObject which is actually a MutableMap.
val json: JsonObject = Parser().parse(jsonData) as JsonObject
The answer provided by Bitwise DEVS may work, but the explanation is incorrect.
It is not necessary to convert the map into an immutable map - it can even be seen in the screenshot of the question: expected (Mutable)Map means that it can be mutable or immutable.
The real problem here is that the called constructor of JSONObject is defined for Map<Any?, Any?> but the given parameter is of type Map<String!, String!>. We know that String is a subtype of Any?, so why is that a problem?
It is a problem because Map is invariant in the key parameter which means that a Map<A, V> is not subtype of Map<B, V> even if A is subtype of B (and also not if it is the other way around).
The call of toMap does not work because it makes the map immutable, but because it is defined as
fun <K, V> Map<out K, V>.toMap(): Map<K, V>
In the receiver type of toMap the key parameter is annotated with the out modifier, meaning that K is covariant here. This means that a Map<Any, V> in this position can safely be considered as a supertype of Map<String, V>. Additionally, Map is always covariant in its value type, meaning that Map<Any, Any> in this position can safely be considered as a supertype of Map<String, String>.
You could as well just cast remoteMessage.data as Map<Any?, Any?> or use toMutableMap, it would be all the same. It has definitely nothing to do with mutability of the map.
Kotlin documentation on variance: https://kotlinlang.org/docs/generics.html#declaration-site-variance
Kotlin documentation of Map: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-map/
Definition of toMap: https://github.com/JetBrains/kotlin/blob/ea836fd46a1fef07d77c96f9d7e8d7807f793453/libraries/stdlib/src/kotlin/collections/Maps.kt#L600
I just realized the answer, if you are using Map like Map<String, String> in Kotlin there is a mutable and immutable version of it. In the question above all you need to do is to convert it to immutable Map using toMap().
val msgData = parser.fromJsonString<CommonNotification>(
JSONObject(remoteMessage.data.toMap()).toString(),
CommonNotification::class.java
) ?: return
Gson is perfect library for this kinda task, here how to do it with gson.
Kotlin implementation,
var map: Map<String, Any> = HashMap()
map = Gson().fromJson(jsonString, map.javaClass)
Or if you want to try with Java,
Gson gson = new Gson();
Map<String,Object> map = new HashMap<String,Object>();
map = (Map<String,Object>) gson.fromJson(jsonString, map.getClass());
And also I just tried with your json-string and it is perfectly working,

Kotlin now provides a multiplatform / multi-format reflectionless serialization.
plugins {
kotlin("jvm") version "1.7.10" // or kotlin("multiplatform") or any other kotlin plugin
kotlin("plugin.serialization") version "1.7.10"
}
repositories {
mavenCentral()
}
dependencies {
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.4.0")
}
So now you can simply use their standard JSON serialization library:
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonObject
fun main() {
val jsonString = "{\"id\":24,\"name\":\"nope\",\"username\":\"unavailable1991\",\"profile_image_90\":\"/uploads/user/profile_image/24/23102ca5-1412-489d-afdf-235c112c7d8e.jpg\",\"followed_tag_names\":[],\"followed_tags\":\"[]\",\"followed_user_ids\":[],\"followed_organization_ids\":[],\"followed_podcast_ids\":[],\"reading_list_ids\":[],\"blocked_user_ids\":[],\"saw_onboarding\":true,\"checked_code_of_conduct\":true,\"checked_terms_and_conditions\":true,\"number_of_comments\":0,\"display_sponsors\":true,\"trusted\":false,\"moderator_for_tags\":[],\"experience_level\":null,\"preferred_languages_array\":[\"en\"],\"config_body_class\":\"default default-article-body pro-status-false trusted-status-false default-navbar-config\",\"onboarding_variant_version\":\"8\",\"pro\":false}"
Json.parseToJsonElement(jsonString) // To a JsonElement
.jsonObject // To a JsonObject
.toMutableMap() // To a MutableMap
}
See: Kotlin Serialization Guide for further details.