https://kotlinlang.org logo
#serialization
Title
# serialization
z

Zakhar

03/07/2024, 3:26 PM
Hello! Facing an issue with the kotlinx json serialization library. Trying to parse a string to
Map<String, JsonElement?>
. All strings in values of the map will have quotes at the start and at the end. E.g instead of just
consumable
a string will look like
"consumable"
How to avoid this? Tried to use org.json.JSONObject. And in this case the result looks correctly.
The string i am trying to parse:
"{\"af_content_id\":\"currency.credits.1\",\"af_content_type\":\"consumable\",\"af_revenue\":1.59,\"af_currency\":\"RUB\"}"
I generate it from javascript code. The
JSON.stringify
function.
👍 1
a

Adam S

03/07/2024, 3:44 PM
that string looks like valid JSON, aside from the escaped quotes. How do you generate that string from JSON stringify?
if you could generate it without the escaped quotes then it should Just Work
z

Zakhar

03/07/2024, 3:51 PM
How do you generate that string from JSON stringify?
The source object:
{af_content_id: "currency.credits.1", af_content_type: "consumable", af_revenue: 1.59, af_currency: "RUB"}
Just a valid js object.
Looks like i have to parse it to
Map<String, String?>
. Maybe
JsonElement
is the issue
e

ephemient

03/07/2024, 7:54 PM
just decode a
JsonObject
, which is a subtype of
Map<String, JsonElement>
z

Zakhar

03/08/2024, 2:52 PM
The
JsonObject
did not help. Still get the same result 😕
c

chr

03/10/2024, 6:08 PM
Both of these work just fine for me:
Copy code
val json: JsonElement = Json.parseToJsonElement(string)
val contentType1 = json.jsonObject["af_content_type"]!!.jsonPrimitive.content

val map: Map<String, JsonElement> = Json.decodeFromString(string)
val contentType2 = map["af_content_type"]!!.jsonPrimitive.content
Just make sure you're using
content
and not
toString()
, because the toString method inserts those quotes to denote that it's a string primitive and not a number primitive (ie: if the content was
"42"
, the quotes disambiguate the string
"42"
from the number
42
Copy code
public override fun toString(): String =
    if (isString) buildString { printQuoted(content) }
    else content
1
z

Zakhar

03/11/2024, 9:14 AM
Yes man you are right. The issue was the
toString
function of
JsonElement
. The AppsFlyer lib requires a Map to log events https://dev.appsflyer.com/hc/docs/android-sdk-reference-appsflyerlib#logevent And looks like the lib uses the
toString
function somewhere inside. Thanks for your help.
2 Views