-
Notifications
You must be signed in to change notification settings - Fork 645
Unwrapping single value JSON arrays to objects #419
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
I would advocate against baking any support for this in. You should be able to accomplish this yourself by writing a custom serializer and using |
@slomkowski I faced the same issue and I quickly developed a "workaround" but that's not really the best way to implement it... Anyway, hope it will help to unblock some devs: import kotlinx.serialization.Decoder
import kotlinx.serialization.Encoder
import kotlinx.serialization.KSerializer
import kotlinx.serialization.SerialDescriptor
import kotlinx.serialization.Serializer
import kotlinx.serialization.encode
import kotlinx.serialization.internal.ArrayListSerializer
import kotlinx.serialization.internal.SerialClassDescImpl
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonElementSerializer
@Serializer(forClass = List::class)
class UnwrapSingleValueArray<T : Any>(private val dataSerializer: KSerializer<T>) : KSerializer<List<T>> {
override val descriptor: SerialDescriptor = object : SerialClassDescImpl("UnwrapSingleValueArray") {}
override fun deserialize(decoder: Decoder): List<T> {
return when (val jsonElt = JsonElementSerializer.deserialize(decoder)) {
is JsonArray -> jsonElt.content.map { jsonClient.parse(dataSerializer, it.toString()) }
else -> listOf(jsonClient.parse(dataSerializer, jsonElt.toString()))
}
}
override fun serialize(encoder: Encoder, obj: List<T>) {
encoder.encode(ArrayListSerializer(dataSerializer), obj)
}
} Note: the |
@slomkowski This is what they are doing:
Otherwise rather use gson and be done. |
how cheap is .reverse on megabytes of inner-json? |
It is a common pattern for APIs to return single object wrapped in an array as in following JSON:
which should be deserialized to:
Jackson already implements this feature, it can be enabled with property
UNWRAP_SINGLE_VALUE_ARRAYS
. More info: FasterXML/jackson-databind#381.It would be nice to have similar option here.
The text was updated successfully, but these errors were encountered: