Home > Net >  What is equals of Gson.fromJson() in Kotlinx.serialization?
What is equals of Gson.fromJson() in Kotlinx.serialization?

Time:01-29

I want to move from Gson to kotlinx.serialization, what is equals of this to kotlinx.serialization ?

private fun parseError(response: Response<*>?) {
      val error = gsonConverter(response?.errorBody()?.charStream())
      // Entire code
      // ....

}

private fun gsonConverter(charStream: Reader?): ErrorResponse {
            return Gson().fromJson(
                charStream, ErrorResponse::class.java
            )
        }

CodePudding user response:

Not exactly the equivalent, but you can directly use the byte stream from the response. You'll still have to handle the case of a null response/body as the decodeFromInputStream does not take a nullable type :

private fun parseError(response: Response<*>?) {
    val error = gsonConverter(response?.errorBody()?.byteStream())
    // Entire code
    // ....

}

private fun gsonConverter(stream: InputStream?): ErrorResponse {
    return stream?.let { 
            Json.decodeFromStream<ErrorResponse>(it) 
    } ?: // A default ErrorResponse for example
}
  •  Tags:  
  • Related