Created
April 12, 2024 04:00
-
-
Save yongjhih/5b6e2594c02605ca7ba31b20ce74b613 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class GsonConverterFactory2(private val gson: Gson = Gson()) : Converter.Factory() { | |
override fun responseBodyConverter(type: Type, annotations: Array<Annotation>, retrofit: Retrofit): Converter<ResponseBody, *> { | |
return GsonResponseBodyConverter2(gson, gson.getAdapter(TypeToken.get(type))) | |
} | |
override fun requestBodyConverter(type: Type, parameterAnnotations: Array<Annotation>, methodAnnotations: Array<Annotation>, retrofit: Retrofit): Converter<*, RequestBody> { | |
return GsonRequestBodyConverter2(gson, gson.getAdapter(TypeToken.get(type))) | |
} | |
} | |
class GsonResponseBodyConverter2<T>( | |
private val gson: Gson, | |
private val adapter: TypeAdapter<T>, | |
) : Converter<ResponseBody, T> { | |
override fun convert(value: ResponseBody): T { | |
val jsonReader = gson.newJsonReader(value.charStream()) | |
return value.use { | |
val result = adapter.read(jsonReader) | |
if (jsonReader.peek() != com.google.gson.stream.JsonToken.END_DOCUMENT) { | |
throw JsonIOException("JSON document was not fully consumed.") | |
} | |
result | |
} | |
} | |
} | |
class GsonRequestBodyConverter2<T>(private val gson: Gson, private val adapter: TypeAdapter<T>) : Converter<T, RequestBody> { | |
companion object { | |
val MEDIA_TYPE = "application/json; charset=UTF-8".toMediaType() | |
} | |
override fun convert(value: T): RequestBody { | |
val buffer = Buffer() | |
gson.newJsonWriter(OutputStreamWriter(buffer.outputStream(), Charsets.UTF_8)).use { jsonWriter -> | |
adapter.write(jsonWriter, value) | |
} | |
return buffer.readByteString().toRequestBody(MEDIA_TYPE) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment