Retrofit 2 — Unwrapping Envelope Responses with Custom Converter

We recently worked on a project where the API wrapped all responses into an envelope. For example, when the app requested the user info, it always got a wrapped response:

{
    "serverInfo": {
        "apiVersion": "0.0.1a"
    },
    "statusCode": 200,
    "payload": {
        "username": "Norman",
        "id": 42
    }
}

The payload was the actual interesting information. Previously, this caused all endpoints to be declared as parameterized envelope types, e.g., Envelope<User>. While this works fine and doesn't have any significant disadvantages besides always having to call envelope.getPayload() throughout the app. Nevertheless, it's not very developer friendly and makes the programmers, who love clean code, make a frowny face.

In this tutorial, you'll learn how to put a smile on your crazy coworkers by getting rid of these parameterized envelope types. All you need is a custom converter to automatically unwrap the envelopes for you and make the payload directly available.

Retrofit Series Overview

  1. Ignore Response Payload with Call<Void>
  2. Receive Plain-String Responses (Coming soon)
  3. Crawl HTML Responses with jspoon (Wikipedia Example) (Coming soon)
  1. Callbacks (Coming soon)
  2. Annotations (Coming soon)
  3. Fluent Interface with Builders (Coming soon)


Continue reading

University Enrollment Required

Future Students benefit from value packed videos and tutorials.

Enroll to receive exclusive content or sign in if you’re already a Future Student.

Enroll me for $12/mo

Explore the Library

Find interesting tutorials and solutions for your problems.

Miscellaneous