Anyone happen to know why my serializer I've writt...
# serialization
s
Anyone happen to know why my serializer I've written for an enum class is failing with this
JsonDecodingException
? What is strange is that it works in certain cases, but fails in others. When I get back this response:
Copy code
{
  "id": 1,
  "status": 1,
  "info": 0
}
It works fine and returns
IN_PROGRESS
. When I get this response:
Copy code
{
  "id": 3,
  "status": 3,
  "info": 0
}
I encounter this error:
Copy code
kotlinx.serialization.json.JsonDecodingException: Invalid JSON at 28: Expected string or non-null literal
Which is thrown from
takeString()
in
JsonReader.kt
after trying to call
decodeInt()
. If both of them were failing I would be a little less confused, but with only one of them failing I am at a loss. Is it interpreting the
3
as a byte or something, and thus failing the
TC_OTHER
and
TC_STRING
check, whereas the
1
is interpreted as a
TC_STRING
somehow? All I can think of 🤔
t
You can use
@SerialId
for automatic serialization
s
ooh, will try it out. thanks! (still curious as to why the above code is returning those results tho..)
t
Enums are serailizable by default
"IN_PROGRESS"
->
<http://StatusCode.IN|StatusCode.IN>_PROGRESS
s
Yes as a string using their declared enum name, but with a parameter & a custom serializer I would expect the above code I listed to work, unless I'm missing something.
t
1. Serializer as separarte object (not companion) 2.
@Serializer(with=...)
on enum
s
Copy code
@Serializable
enum class StatusCode {
    @SerialId(1) IN_PROGRESS,
    @SerialId(2) SHOULD_RETRY,
    @SerialId(3) SHOULD_NOT_RETRY;
}
With this response:
Copy code
{
  "id": 1,
  "status": 1,
  "info": 0
}
Produces:
Copy code
kotlinx.serialization.SerializationException: StatusCode does not contain element with name '1'
I'll try it with a separate serializer as its custom serializer besides the companion object
Ah, no that has the same error as the first one.
Just going to map it from an Int after the call is made for now, will revisit this later
t
SerialId
doen’t work in your cases?
s
I did try, it gave me the error I listed above, the
StatusCode does not contain element with name '1'
. Not sure if I implemented it correctly or not, couldn't find solid information on how I was supposed to use it unfortunately, just a few scattered examples.
t
Int wrap required 😞
n
not sure if this was mentioned before but this
Copy code
values().first {
            it.code == decoder.decodeInt()
        }
    }
seems like it takes a new int from the decoder for each comparison, so it might not have more data it would make more sense to decode the value and then search in
values()
👌 2