Kotlin Serialisation with Enum (kotlinx.serialisation library) - android

I am using kotlinx.serialisation and had a question.
I have JSON like this:
{
"state": "bad"
}
state can return bad|good|near_good
My State data class looks like this:
#Serializable
internal enum class State {
#SerialName("good") GOOD,
#SerialName("bad") BAD,
#SerialName("near_good") NEAR_GOOD
}
Is it possible to have the enum names remain all caps like this, while parsing the json value that is returned?
Right now when I test this, the parsed json data returns as GOOD|BAD|NEAR_GOOD, because the enum name is uppercase.
Hopefully the question makes sense.
Appreciate any answers.
EDIT (Updated for clarity)
Right now I have a test that checks:
assert(state.name == "bad")
This fails because with the way I mentioned it above (#SerialName("bad") BAD), the state.name is equal to 'BAD'.
I want the enum name to be uppercase, as per enum naming convention, but I want the value to be lowercase as per the JSON.
I can fix the failing test by changing it to be
#SerialName("bad") bad
I'm not sure if it is possible or maybe I am doing something in the wrong way, but I hope this clarifies.
Thanks!

I guess the problem is your test. It's not very robust to check for string equality. You have powerful compile-time guarantees with enums, so I would suggest to just compare enum values, not strings:
assert(state == State.BAD)
If you're trying to test the serial name of the enum value, then... don't? That's the job of Kotlinx Serialization's tests to verify that the annotations work correctly.

name is the wrong property to use for this purpose. It is documented as:
Returns the name of this enum constant, exactly as declared in its enum declaration.
What you could possibly do instead is to define a property (and, if you like, toString) for your enum class as follows:
val serialName =
declaringJavaClass.getField(name)
.getAnnotation(SerialName::class.java)
.value
// optionally set toString
override fun toString() = serialName
And then you can print it like this: println(state.serialName)
Or like this: println(state)
But the real question is:
Why do you want to do that?
The whole point of the SerialName name annotation is to parse the serialized value to your enum variable, and to encode your enum variable to the serialized value. The value of your enum variable itself is independent from the serialized value and remains an object (State.BAD etc) rather than a string.

Related

How does differentiate between Serialized data class and normal Serialized class?

While writing code for RecyclerView to get data I figured out there's a data class in Kotlin.
Following codes are taken from two different projects which are linked above.
#Serializable
data class MarsPhoto(
val id: String,
#SerialName(value = "img_src")
val imgSrc: String
)
class Contacts {
#SerializedName("country")
private val country:String? = null
fun getCountry():String?{
return country
}
}
I know that both classes are doing same job. So what does differentiate them? I also wonder in the MarsPhoto data class how they can get the id without declaring SerialName just the way they did for imgSrc. (I am just on the way to learning kotlin now, so I'm absolute beginner).
Basically for "data" class the compiler automatically derives the following members from all properties declared in the primary constructor:
equals()/hashCode() pair
toString() of the form "MarsPhoto(id=1, imgSrc=asdf)"
componentN() functions corresponding to the properties in their order of declaration.
copy()
You can read a lot more at enter link description here
On the SerializedName part of your question. if you are dealing with Gson lib by default it is using fields name as "SerializedName". And only if you want to use something different then field name, you can use SerializedName annotation and pass your custom value there. But usually, everybody just writes #SerializedName() with duplication of field names as value for every field.
It's a good idea if you are receiving and Serializing data from server from Json. Because Backend developers can use a bad keys in response, which you don't want to use in your code, so #SerializedName will be the only place where you will have to see this key, and you can name your fields however you like.
#Serializable used to mark class as serializable to disk or like into a file( alternative is Parcel able in android) special useful in case of process death or configuration changes and #SerializedName("country") used for json parsing when u receive the response from server
You get the id without #SerializedName because the JSON property field is the same as your variable name, but imgSrc and img_src is not. Still, even if they are the same, you should always use #SerializedName, because your variable names could be converted to random letters during code optimization, and obfuscation.

android Room with kotlin value class?

I'm trying to use a room entity with a value class:
#JvmInline
value class UserToken(val token: String)
and the entity:
#Entity(tableName = TABLE_AUTH_TOKEN)
data class TokenEntity(
#PrimaryKey val id: Int = 0,
val token: UserToken
)
I get the following error:
error: Entities and POJOs must have a usable public constructor. You can have an empty constructor or a constructor whose parameters match the fields (by name and type).
public final class TokenEntity {
^
is it even possible to use room with value class? I couldn't find anything about this. thanks
See the comment from #CommonsWare. Android does not yet support value classes for Room.
The same holds true for the value classes introduced in kotlin 1.5. The type is not supported.
— Support Inline class in Room entity
Here is a possible explanation according to Kotlin Inline Classes in an Android World.
Looking to solve this you could try and add a TypeConverter for your Inline class, but since your Inline class is just the value it wraps when it’s compiled, this doesn’t make much sense and it doesn’t work as you’d expect even if you tried...
I’m just guessing it’s because this is a TypeConverter converting UserId to Int which is basically the same as Int to Int 😭. Someone will probably solve this problem, but if you have to create a TypeConverter for your Inline class then you are still plus one class for the count (multidex). 👎
I think yes if you can provide a type converter for it to change it to some sort of primitive data type (int , string, long ...etc) when it needs to be stored, and to change it back to its class type when it's fetched from database.
You can read about Type Converters from here
Referencing complex data using Room
other than that, your other class should be an entity and bind both your entities together using a Relation.
at least that's what I know about how to use Room.
UserToken always will have only one attribute? In this case, you don't need two classes, just use token: String directly on your entity class;
If you really need keep this class, you have two options:
TypeConverter, where you basically will convert the object into a json, and save as string in the database;
Relation, where you will transform the UserToken in a entity, and on TokenEntity save the tokenId.

Android data model with only the fields that I need

If I make use of Retrofit and a data model. Does the data model need to have all the fields that the API returns? I only need some fields.
No, you don't have to write all the fields that the API is returning. You can only write the fields that you want, and leave the rest of them as is.
Also, as a side note, don't forget to add annotations to your model variables using #SerializedName("key") to allow Serialization and deserialising of objects, just something to keep in mind while working with API's.
No it is not requirement. If you need only one field just declare one field and only this field will obtain its value. However, you should note that, declaring only some field does not mean you only receive value of these fields. You will get receive all field but Gson converter produces compact java object for you
It is not required, if the values are not needed, just don't add them. However, if they come or not in the response you can use nullable operator (?) of kotlin, so you can handle whereas it come or not.
In this example, if phone is present in the response it is parsed. And if it's not present it is not parsed. If you do not use (?) operator and phone is not present it throws and exception.
data class AdMessage(#SerializedName("body") val message: String,
#SerializedName("email") val email: String,
#SerializedName("name") val name: String,
#SerializedName("phone") val phone: String?)

How to integrate Kotlin inline class with Android data binding?

Kotlin introduced inline class which is strong typed type alias. This can be useful when use with database. For example,
inline class Age(val value: Int)
inline class Height(val value: Int)
When they are written to database, they are compiled to Int but Kotlin can prevent you accidentally putting a Height into a Age Field. If you use type alias or Int directly, it is possible with type alias but inline class produces a compile time error.
However, these also cause problems with Android data binding. I get data binding error when I try to bind a String inline class to a String attribute.
While it is possible to write some kinds of adapter to bypass this, but it defeat the purpose of using inline class and not practical for creating adapters for all inline classes.
I would like to ask are there any elegant ways to solve this issue?
First thing you need to understand is inline classes are not just wrappers around primitive types. They are more than type Aliases.
Now coming to your example, even though DataBinding has the understanding that if you put any MutableLiveData<T> instance in xml, it will take that value of that particular variable(something like mutableLiveData.value). But if you put MutablLiveData<Age>, mutableLiveData.value will always be of Type Age but not type Int.
Note that inline class, creates a completely new type and not just a type alias.
I believe that you somehow need a method in your data binding, that returns the value contained in the inline class object.

Swift to Kotlin: Struct to Data Class Example

I have converted the following Swift code:
struct FooModel: Decodable {
public let id: String
public let bars: [[BarModel]]
}
to this Kotlin code:
data class FooModel (val id: String, val bars: List<List<BarModel>>)
The issue I am encountering, is my id is coming in null for the Kotlin code (via gson). Everything else in the Kotlin conversion is working fine and the entire JSON is populating all data classes, except for this tiny piece (the id variable).
I suspect my conversion here is the cause, any ideas?
If the id should be nullable do it like this:
data class FooModel (
val id: String?,
val bars: List<List<BarModel>>
)
The question mark makes this property nullable.
If the JSON you are getting is correct (the id value is there and coming to you as a string), your code should work. It's unclear what could be going wrong here if that's the case.
However, it is worth knowing that there is a big potential "gotcha" with Gson that you should be aware of: it's possible to declare a variable of a data class as non-nullable but still get a null after conversion. This can happen when an expected value is missing from the JSON response. In these cases Gson does not throw an error and I only found out later when I got a crash trying to access the non-nullable variable that should never have made it to me as null. I discovered this is a consequence of Gson using something like Class.newInstance() instead of a regular constructor when it creates these data classes, and then uses reflection to populate the data. More is written about this in another answer here: Why Kotlin data classes can have nulls in non-nullable fields with Gson?
Depending on your use case you might consider this to be a design flaw and a reason to avoid Gson in favor of other JSON serialization libraries. My personal favorite at the moment is Square's Moshi.
You can check if the value type you are getting from server matches with your variable id i.e. String on both the sides. Secondly you can try using SerializedName("id") included in library:
implementation 'com.google.code.gson:gson:2.9.0'

Categories

Resources