0

I am migrating my project serialization client from GSON to KotlinxSerialization and Faced a problem: All responses from API inherit an abstraction class for example:

abstract class BaseResponse <T> (
val type: String? = null,
val payload: T? = null){

When I try to get a response from the API, I use the class

@Srializable
class LoginResponse: BaseResponse <LoginResponse.LoginPayload> (){

class LoginPayload(val s: Int)

}

and getting serialization error java.lang.NoSuchFieldError: No field typeSerial0 of type Lkotlinx / serialization / KSerializer; in class Lru / .../ response / LoginResponse $$ serializer; or its superclasses

As I understand it, the deserializer tries to deserialize the fields of the parent class first and does not understand how to deserialize the payload. Spent two days on this problem, and I don't know how to solve it.

  • 1
    can you add sample JSON you're trying to serialize? – Pawel Mar 19 '21 at 12:30
  • JSON response for example {"type":"Success","payload":{"s":"someText"}} – Gennadiy Mar 19 '21 at 21:41
  • With this structure looks like it's impossible to initialize `BaseResponse`. `LoginResponse` calls 0-arg constructor which means `type` and `payload` are set as null and cannot be be modified. If this worked with GSON it's probably because that lib is deprecated and it relies heavily on reflection so it could forcefully modify those fields. I suggest just changing `BaseResponse` to have no constructor parameters and those field to be abstract so they have to be implemented by all responses (preferably in constructor). – Pawel Mar 19 '21 at 23:44
  • Yes, I also came to this decision. I just made the payload field abstract in the BaseResponse class, and redefined it in other classes that inherit it. Pawel, thanks for the help, helped a lot. – Gennadiy Mar 21 '21 at 10:21
  • Besides the point that serializing generics can be tricky, which might be what is going on here, you should apply `@Serializable` to `LoginPayload` as well. Could you add the actual code which causes the exception, i.e., are you serializing/deserializing, using which encoder/serializer? – Steven Jeuris May 18 '21 at 22:37

0 Answers0