0

Below is a description of the data structure of the data I need the Android app to pass to the REST API in JSON form. Of particular note is the "response" field, which varies in type. Sometimes it is a boolean, sometimes an integer, or it can be a string or an array of integers. For various reasons the server API cannot easily be changed so I have to support it as is.

How can I customise my Retrofit use to cater to a field that varies in data type like this? I've previously written type adapters for Retrofit's rest adapter and that works great for handling responses, but what is the equivalent of a type adapter for requests?

array(
        array(
                question_id => 1,
                route_id => 1,
                response => true,
                timestamp => ‘2014-01-01 20:01:01'
        ),
        array(
                question_id => 2,
                route_id => 1,
                response => ’this is a string',
                timestamp => ‘2014-01-01 20:01:01'
        ),
        array(
                question_id => 3,
                route_id => 1,
                response => 1,
                timestamp => ‘2014-01-01 20:01:01'
        ),
        array(
                question_id => 4,
                route_id => 1,
                response => array(
                        1234,
                        178,
                        109
                ),
                timestamp => ‘2014-01-01 20:01:01'
        ),
)
Ollie C
  • 28,313
  • 34
  • 134
  • 217
  • possible duplicate of [How to handle Dynamic JSON in Retrofit?](http://stackoverflow.com/questions/24279245/how-to-handle-dynamic-json-in-retrofit) – dominik4142 Oct 17 '14 at 09:09

2 Answers2

1

It turns out this is supremely easy. If Retrofit is passed objects of type Object within the model class, it intelligently converts them to the right JSON field type.

public class MyModel {

    // Renders to JSON as boolean, int, String etc depending on the underlying class
    public Object response; 

}
Ollie C
  • 28,313
  • 34
  • 134
  • 217
0

You can supply your own json converter that would handle it internally. How to handle Dynamic JSON in Retrofit?

Community
  • 1
  • 1
dominik4142
  • 556
  • 3
  • 14