Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ktor with kotlinx serialization: how to use JSON.nonstrict

I'm trying to initialize Ktor http client and setup json serialization. I need to allow non-strict deserialization which JSON.nonstrict object allows. Just can't get how to apply this setting to serializer.

 val client = HttpClient {
                install(JsonFeature) {
                    serializer = KotlinxSerializer()                    
                }
        }
like image 510
Rodion Altshuler Avatar asked Nov 29 '18 20:11

Rodion Altshuler


2 Answers

After Kotlin 1.4.0 released:

use this for converting string to Object:

val response = Json {
    ignoreUnknownKeys = true
}.decodeFromString(ResponseObject.serializer(), jsonString)

And for your httpClient use:

HttpClient {
    install(JsonFeature) {
        serializer = KotlinxSerializer()
    }
    install(Logging) {
        logger = Logger.DEFAULT
        level = LogLevel.ALL
    }
}
like image 92
Dr.jacky Avatar answered Dec 02 '22 09:12

Dr.jacky


You can specify json configurations using the Json builder, which you pass into the KotlinxSerializer.

val client = HttpClient {
    install(JsonFeature) {
        serializer = KotlinxSerializer(Json {
            isLenient = true
            ignoreUnknownKeys = true
        })                    
    }
}

The exact fields for the Json builder is experimental and subject to change, so check out the source code here.

like image 39
Jacques.S Avatar answered Dec 02 '22 07:12

Jacques.S