Created
June 6, 2019 12:44
-
-
Save gotev/7da9b72bce95f6cb21416b9fc5c2380d to your computer and use it in GitHub Desktop.
Extended Gson Factory
This file contains hidden or 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
import com.google.gson.Gson | |
import com.google.gson.TypeAdapter | |
import com.google.gson.reflect.TypeToken | |
import okhttp3.RequestBody | |
import okhttp3.ResponseBody | |
import retrofit2.Converter | |
import retrofit2.Retrofit | |
import retrofit2.converter.gson.GsonConverterFactory | |
import java.lang.reflect.Type | |
/** | |
* This class supports using gson type adapters also for | |
* @Field, @FieldMap, @Header, @HeaderMap, @Path, @Query and @QueryMap | |
* | |
* By default Retrofit uses type adapters only for request/response body parameters. | |
* When you have bad API design, recurring to this solutions becomes a necessity. You can't defeat dumbness so easily. | |
*/ | |
class ExtendedGsonConverterFactory( | |
private val gson: Gson, | |
private val wrapping: GsonConverterFactory = GsonConverterFactory.create(gson) | |
) : Converter.Factory() { | |
override fun responseBodyConverter( | |
type: Type, | |
annotations: Array<Annotation>, | |
retrofit: Retrofit | |
): Converter<ResponseBody, *>? { | |
return wrapping.responseBodyConverter(type, annotations, retrofit) | |
} | |
override fun requestBodyConverter( | |
type: Type, | |
parameterAnnotations: Array<Annotation>, | |
methodAnnotations: Array<Annotation>, | |
retrofit: Retrofit | |
): Converter<*, RequestBody>? { | |
return wrapping.requestBodyConverter(type, parameterAnnotations, methodAnnotations, retrofit) | |
} | |
override fun stringConverter( | |
type: Type, | |
annotations: Array<Annotation>, | |
retrofit: Retrofit | |
): Converter<*, String>? { | |
return StringConverter(gson.getAdapter(TypeToken.get(type))) | |
} | |
private class StringConverter<T>(private val typeAdapter: TypeAdapter<T>) : Converter<T, String> { | |
override fun convert(value: T): String? { | |
val json = typeAdapter.toJson(value) | |
return if (json.startsWith("\"") && json.endsWith("\"")) { | |
json.substring(1, json.lastIndex) | |
} else { | |
json | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment