dave08
JsonContentNegotiationTest
class MoshiSerializer(block: Moshi.Builder.() -> Moshi.Builder = { this }) : ContentConverter { private val backend: Moshi = Moshi.Builder().apply { block() }.build() override suspend fun deserialize(charset: Charset, typeInfo: TypeInfo, content: ByteReadChannel): Any? { try { return backend.adapter<Any>(typeInfo.reifiedType).fromJson(content.toInputStream().source().buffer()) } catch (e: JsonDataException) { throw JsonConvertException(e.message ?: "", e) } } override suspend fun serializeNullable( contentType: ContentType, charset: Charset, typeInfo: TypeInfo, value: Any? ): OutgoingContent? { if (value == null) return TextContent("null", ContentType.Application.Json) return TextContent(backend.adapter<Any>(typeInfo.reifiedType).toJson(value), contentType) } } fun Configuration.moshi( contentType: ContentType = ContentType.Application.Json, block: Moshi.Builder.() -> Unit = {} ) { val builder = Moshi.Builder() builder.apply(block) val converter = MoshiSerializer() register(contentType, converter) }
Aleksei Tirman [JB]
JsonDataException
deserialize
EOFException
A modern programming language that makes developers happier.