Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 284 Vote(s) - 3.57 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Type mismatch when serializing data class

#1
I'm following [this example](

[To see links please register here]

) to serialize a data class. When I do so, I get this build error:
```
Type mismatch: inferred type is Data but SerializationStrategy<TypeVariable(T)> was expected
```

Here's my code:
```
import kotlinx.serialization.json.Json
import kotlinx.serialization.Serializable

@Serializable
data class Data(val a: Int, val str: String = "str")

fun main() {
println(Json.encodeToString(Data(42)))
}
```

Since I am using the @Serializable annotation, shouldn't I have the right data type? How can I serialize the data class?
Reply

#2
I was using the wrong ```encodeToString()``` function. It has to be ```kotlinx.serialization.encodeToString```, not the one from ```kotlinx.serialization.json.Json```
Reply

#3
Please check the imports.
The ones below come from kotlin serialization and needs just the string and the object respectively.

```
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
```
Reply

#4
The function that only requires the value parameter is implemented as an extension function, so you need to add import
```kotlin
import kotlinx.serialization.encodeToString
```
To make it clear: instead of
```kotlin
import kotlinx.serialization.json.Json
import kotlinx.serialization.Serializable
```
you must write
```kotlin
import kotlinx.serialization.json.Json
import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToString
```
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through