All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.github.andreabrighi.converter.RetrofitJsonConverterFactory.kt Maven / Gradle / Ivy

There is a newer version: 1.0.25
Show newest version
package io.github.andreabrighi.converter

import com.google.protobuf.GeneratedMessageV3
import com.google.protobuf.MessageOrBuilder
import com.google.protobuf.util.JsonFormat
import okhttp3.MediaType
import okhttp3.RequestBody
import okhttp3.ResponseBody
import retrofit2.Converter
import retrofit2.Retrofit
import java.lang.reflect.Type

/**
 * A [Converter.Factory] which uses Protobuf's [JsonFormat] for serialization and deserialization of
 * JSON.
 * This converter only applies for classes generated by the Protobuf compiler.
 */
class RetrofitJsonConverterFactory private constructor() : Converter.Factory() {

    override fun responseBodyConverter(
        type: Type,
        annotations: Array,
        retrofit: Retrofit,
    ): Converter {
        return Converter { value ->
            val structBuilder = (type as Class<*>).getMethod("newBuilder").invoke(null) as GeneratedMessageV3.Builder<*>
            JsonFormat.parser().ignoringUnknownFields().merge(value.string(), structBuilder)
            structBuilder.build() as MessageOrBuilder
        }
    }

    override fun requestBodyConverter(
        type: Type,
        parameterAnnotations: Array,
        methodAnnotations: Array,
        retrofit: Retrofit,
    ): Converter<*, RequestBody> {
        return Converter { value ->
            RequestBody.create(
                MediaType.parse("application/json; charset=utf-8"),
                JsonFormat.printer().print(value as MessageOrBuilder),
            )
        }
    }

    /**
     * Create an instance using `RetrofitJsonConverterFactory.create()`.
     */
    companion object {
        /**
         * Create an instance using of RetrofitJsonConverterFactory.
         */
        fun create(): RetrofitJsonConverterFactory {
            return RetrofitJsonConverterFactory()
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy