Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JsonElement should expose the original value #1799

Closed
bluenote10 opened this issue Dec 20, 2021 · 4 comments
Closed

JsonElement should expose the original value #1799

bluenote10 opened this issue Dec 20, 2021 · 4 comments
Labels

Comments

@bluenote10
Copy link

What is your use-case and why do you need this feature?

I'm working with raw schema-less JSON data, i.e., I need to use the plain JsonElement class. The use case involves accessing the underlying value wrapped by JsonElement.

Currently this is awkward and inefficient, because the JsonElement only exposes the underlying value in the form of a String. This requires repeated re-parsing of the string (plus incorporating the isString information) to get e.g. actual boolean/number values etc.

Describe the solution you'd like

I'm completely new to Kotlin, so I lack the skills to draft an ideal solution.

What I would have expected from a user perspective is that the JsonElement is modeled like JSON data is modeled in other languages, i.e., with explicit (sealed) subclasses for JsonString, JsonNumber, JsonBoolean, JsonNull, JsonArray, JsonObject, where all e.g. x.value of the appropriate type.

@bluenote10
Copy link
Author

It should be noted that the extension functions defined on JsonPrimitive don't fully solve that issue, because they lose type information. For instance JsonPrimitive("true") allows to extract a boolean although it wasn't constructed from a boolean. My use case also involves maintaining accurate type information.

@sandwwraith
Copy link
Member

What I would have expected from a user perspective is that the JsonElement is modeled like JSON data is modeled in other languages, i.e., with explicit (sealed) subclasses for JsonString, JsonNumber, JsonBoolean, JsonNull, JsonArray, JsonObject

Well, there are JsonObject, JsonArray, JsonPrimitive and JsonNull, so you can do

when(element) {
  is JsonObject -> ...
  is JsonArray -> ...
  is JsonNull -> ....
  else -> ...
}

Does it solve your problem?

Regarding type information in JsonPrimitive: see #1298 (comment)

@bluenote10
Copy link
Author

No, because JsonPrimitive mixes strings, numbers, booleans, and nulls into a field content: String. The original value is lost, and if you look into how e.g. JsonPrimitive.boolean is implemented you can see the inefficient re-parsing I was referring to.

@sandwwraith
Copy link
Member

Then it's a duplicate of #1298, I answered you there

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants