Last active
July 6, 2023 23:48
-
-
Save oldergod/72e96816473c950f9910db35764194d7 to your computer and use it in GitHub Desktop.
Retrofit: Xml or Json converter
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
public class XmlOrJsonConverterFactory extends Converter.Factory { | |
final Converter.Factory xml = SimpleXmlConverterFactory.create(); | |
final Converter.Factory gson = GsonConverterFactory.create(); | |
@Override | |
public Converter<ResponseBody, ?> responseBodyConverter( | |
Type type, Annotation[] annotations, Retrofit retrofit) { | |
// Retrofit gives us all the annotations so we just need to check | |
for (Annotation annotation : annotations) { | |
if (annotation.annotationType() == Xml.class) { | |
return xml.responseBodyConverter(type, annotations, retrofit); | |
} | |
if (annotation.annotationType() == Json.class) { | |
return gson.responseBodyConverter(type, annotations, retrofit); | |
} | |
} | |
// There is no annotation so we cannot handle it | |
return null; | |
} | |
} | |
// and my service would be something like | |
@Json | |
@POST("/some/rest/api") | |
Call<Stuff> getStuff(); | |
@Xml | |
@POST("/some/soap/api") | |
Call<OtherStuff getOtherStuff(); | |
// and we would simple build retrofit with | |
new Retrofit.Builder() | |
.addConverterFactory(new XmlOrJsonConverterFactory()) | |
.build(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment