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

GSON ignoring kotlin data class null-safety and default value #1657

Open
Mopriestt opened this issue Feb 20, 2020 · 4 comments
Open

GSON ignoring kotlin data class null-safety and default value #1657

Mopriestt opened this issue Feb 20, 2020 · 4 comments
Assignees
Labels
kotlin Issues concerning the use of Gson with Kotlin

Comments

@Mopriestt
Copy link

This results in Gson creating data objects with possible null values for non-null variables in the following cases:
Any variable that is marked as non-null in the data class but is missing in the JSON
Any variable that is an Enum type and the value passed from the server doesn’t have a matching Enum value on the client

@lyubomyr-shaydariv
Copy link
Contributor

Duplicate of #1148, #1444 and #1550 .

@paulschuetz
Copy link

this issue is so crucial in my opinion... Is there an update?

@aljidy
Copy link

aljidy commented Jul 19, 2021

Is this not intentional behaviour? See this:

https://stackoverflow.com/a/45793703

Edit: Found the issue. GSON uses the magic sun.misc.Unsafe class which has an allocateInstance method which is obviously considered very unsafe because what it does is skip initialization (constructors/field initializers and the like) and security checks. So there is your answer why a Kotlin non-nullable field can be null. Offending code is in com/google/gson/internal/ConstructorConstructor.java:223

Some interesting details about the Unsafe class: http://mishadoff.com/blog/java-magic-part-4-sun-dot-misc-dot-unsafe/

@sparklexin
Copy link

You can use https://github.com/square/moshi, if null-safety check failed, it will throw an exception.

If you want kotlin data class null-safety and default value using moshi, you can reference https://github.com/sparklexin/moshi-kotlin-nullsafe

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
kotlin Issues concerning the use of Gson with Kotlin
Projects
None yet
Development

No branches or pull requests

6 participants