io.github.andreabrighi.converter.RetrofitJsonConverterFactory.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of RetrofitProtobufJsonConverter Show documentation
Show all versions of RetrofitProtobufJsonConverter Show documentation
Factory for retrofit that can convert a Json request into a Protobuf class
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()
}
}
}