kotlinx.serialization
kotlinx.serialization copied to clipboard
Cannot generate external serializer: class is defined in another module
Describe the bug Can't generate external serializer for a 3rd party Kotlin class in Android project. 3rd party class is like by definition class from "another module" why I can't serialize it that way?
Simplified example for problem:
I have Example class in :mylibrary module
data class Example(val name: String)
In :app module I try to encode it
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val example = Example("test")
val text = Json.encodeToString(ExampleSerializer, example)
}
}
@OptIn(ExperimentalSerializationApi::class)
@Serializer(forClass = Example::class)
object ExampleSerializer
Output:
Error: Cannot generate external serializer 'ExampleSerializer': class 'Example' is defined in another module
To Reproduce serialization.zip
Expected behavior External serializer generated succesfully
Environment
- Kotlin version: 1.9.20
- Library version: plugin:1.9.20, json:1.6.1
- Kotlin platforms: JVM
- Gradle version: 8.4
- IDE version: Android Studio Giraffe | 2022.3.1 Patch 4
- Other relevant context: Mac OS, M1
@nvkleban Did you ever get the solution to this or at least the cause?
@melvinotieno unfortunately no, we just don't use this approach, still waiting this to be fixed though
@nvkleban, which solution did you end up using?
@melvinotieno we just don't use this feature
Is there really any technical restriction why this shouldn't be working? The limitation seems to be quite arbitrary...
Is there really any technical restriction why this shouldn't be working? The limitation seems to be quite arbitrary...
This is technical limitation due to the features of the compiler. Each module is compiled independently of each other. At most, there is access to the bytecode and Kotlin metadata of the dependency, but this is not enough to create a correct serializer (for example, to get the default values)
but this is not enough to create a correct serializer (for example, to get the default values)
I see, thanks.