androidkotlinjacksonretrofitretrofit2

How to convert XML response with Retrofit to data classes


I'm trying to connect to an api that returns an XML. I'm trying to do it with retrofit. I created a data class structure to parse the XML, already with the XML structure. I now need to parse the retrofit response to XML and I read that for that you must use addConverterFactory and put a converter on it. I read that Jackson can parse XML, and that SimpleXML is deprecated, so I tryed with jackson like this:

Retrofit.Builder()
            .baseUrl("https://www.myapi.com/")
            .addConverterFactory(JacksonConverterFactory.create())
            .build().create(DataApiService::class.java)

The problem is that when I execute my app, I got this exception:

Exception in thread "AWT-EventQueue-0" com.fasterxml.jackson.core.JsonParseException: Unexpected character ('<' (code 60)): expected a valid value (JSON String, Number, Array, Object or token 'null', 'true' or 'false')

So seems that Jackson thinks that the response is json, but is XML. How can I do this correctly?

Can't find the solution on Jackson documentation


Solution

  • Solved it, the key was using XmlMapper().registerKotlinModule() when initializing the Jackson converter:

    implementation("com.squareup.retrofit2:retrofit:2.11.0")
                implementation("com.squareup.retrofit2:converter-jackson:2.11.0")
                implementation("com.fasterxml.jackson.module:jackson-module-kotlin:2.18.2")
                implementation("com.fasterxml.jackson.dataformat:jackson-dataformat-xml:2.13.0")
    
    
    Retrofit.Builder()
                .baseUrl("https://www.website.com/")
                .addConverterFactory(JacksonConverterFactory.create(XmlMapper().registerKotlinModule()))
                .build().create(CustomApiService::class.java)
    

    It was hard to discover this, the documentation is not good, so I hope this will help someone in the future.