Search code examples
mappingdeserializationretrofit2json-deserializationenvelope

Retrofit custom deserializer - object as envelope


I need to write custom retrofit deserializer, but don't now where to start. The problem is that every response has it's own result wrapper with envelope. Exampe: post("getUser") would return User (in "Result")

{
    "GetUserResult": {
        "ErrorCode": 0,
        "ErrorDescription": null,
        "Result": {
             "id": ...
        }
    }
}

and post("getPictures") would return list of pictures (in "Result")

{
    "GetPicturesResult": {
        "ErrorCode": 0,
        "ErrorDescription": null,
        "Result": [ { ... } ]
    }
}

and post("getComment") would return comment

{
    "id": ...
    ...
}

So, idea is to have custom deserializer to deserialize "Get*Result" to "Result" object with errorCode, errorDesc and actual data from Result node.

Writing "Get*Result" classes is not an option since there are more than 100 different calls of that type.


Solution

  • Solved with interceptor that gets last part of request path and adds "Result" on the end, checks if response has "Get*Result" JSON element and returns its value, else, returns original response.