Michael Eilers Smith
Michael Eilers Smith

Reputation: 8608

How to post JSON but get XML response using Retrofit?

I have a particular webservice that expects a JSON as post, and will spit back an XML. I'm using Retrofit for all my network calls. Here is how I set the Retrofit adapter with the XML converter:

mRestAdapter = new RestAdapter.Builder()
                    .setEndpoint(getBaseUrl())
                    .setConverter(new SimpleXMLConverter())
                    .build();

As you can see, I'm not using the Gson converter. How can I manage to post any JSON? Thanks!

Upvotes: 1

Views: 2514

Answers (1)

Nikola Despotoski
Nikola Despotoski

Reputation: 50588

Create custom Converter. That will use different converters for serialization and deserialization.

public class MixedConverter implements Converter {
      private Converter mSerializer;
      private Converter mDeserializer;

    public MixedConverter(Converter serializer, Converter deserializer) {
        mSerializer = serializer;
        mDeserializer = deserializer;
    }


    @Override
    public Object fromBody(TypedInput body, Type type) throws ConversionException {
        return mDeserializer.fromBody(body, type);
    }

    @Override
    public TypedOutput toBody(Object object) {
        return mSerializer.toBody(object);
    }
}

Usage:

.setConverter(new MixedConverter(new SimpleXMLConverter(), new GsonConverter(gson)));

Upvotes: 7

Related Questions