'why addConverterFactory is need in Retrofit
My question is around Retrofit and GSON. I know GSON is used for JAVA object <-> JSON . I know that Retrofit parses our response. What i don't understand is why we need GsonConverterFactory .Also why is addConverterFactory needed in retrofit
Solution 1:[1]
UPDATE:
Pojo objects in Kotlin are data classes and annotation use is as in Java
ANSWER:
If your application is Restful, so gets and sends data from / to server
Converter factory need to be added, just for retrofit can convert JSON data (got from server) into java (model) objects (POJO), to use in Android Project.
There are some converter libraries for converting JSON to Java objects, (GSON, Jackson..etc) you have to decide which converter you want to use in your project and add same factory
Dependencies in app.gradle
implementation "com.squareup.retrofit2:converter-gson:VERSION"
and Factories in Retrofit settings
GsonConverterFactory or JacksonConverterFactory
Retrofit.Builder().addConverterFactory(GsonConverterFactory.create());
Also if the remote data type is XML, you need to add SimpleXmlConverterFactory
Solution 2:[2]
if the json converters don't meet your needs you'll need to Add a customized converter factory for serialization and deserialization of your objects. consider this case. i wish you'll find this article helpful.
Solution 3:[3]
The world is not just json and gson. There are other formats that you can use to implement Rest Apis, i.e. XML.
Also, in the world of json parsers there's not only gson but way more like Jackson and Moshi.
It would be extremely difficult to maintain all possible format converters inside Retrofit, so it offloads the parsing to classes that implement the interface for a converter. Putting this behind a factory lets Retrofit decouple even the creation of these converters, so it can have different ones for different responses and requests.
This also allows you to have multiple converters within the same Retrofit instance and it's also an easy way to let you implement your own converter.
All in all, this decoupling allows for way more flexibility than coupling it with specific libraries.
Solution 4:[4]
If you are using Spring, you should create a mapper configuration (or use a default, like in this example), in the retrofit configuration, you should att this code:
@Bean
fun retrofitBuilder(): Retrofit.Builder {
return Retrofit.Builder()
.addConverterFactory(JacksonConverterFactory.create(ObjectMapper()))
}
Then, in your application could read and write Kotlin data class Json, even with no @ information.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | med.Hamdan |
| Solution 3 | Fred |
| Solution 4 | Jhonatan S. Souza |
