title: GSON deserialization of a wrapped list of objects
body: <p>I am trying to de-serialize a list of objects from a JSON response. The JSON array has a key, which is causing issues with using GSON to de-serialize it.</p>
  
  <p>I have about 20 objects similar to this.</p>
  
  <pre><code>public class Device extends Entity {
    String device_id;
    String device_type;
    String device_push_id;
  }
  </code></pre>
  
  <p>For most there is an API method which returns a list of objects. The returned JSON looks like this. Because of other clients, changing the format of the JSON is not a reasonable option at this point.</p>
  
  <pre><code>{
     "devices":[
        {
           "id":"Y3mK5Kvy",
           "device_id":"did_e3be5",
           "device_type":"ios"
        },
        {
           "id":"6ZvpDPvX",
           "device_id":"did_84fdd",
           "device_type":"android"
        }
     ]
  }
  </code></pre>
  
  <p>In order to parse this type of response I'm currently using a mix of <code>org.json</code> methods and Gson.</p>
  
  <pre><code>JSONArray jsonResponse = new JSONObject(response).getJSONArray("devices");
  
  Type deviceListType = new TypeToken&lt;List&lt;Device&gt;&gt;() {}.getType();
  ArrayList&lt;Device&gt; devices = gson.fromJson(jsonResponse.toString(), deviceListType);
  </code></pre>
  
  <p>I'm looking for a cleaner method of doing the deserialization as I'd like to use Retrofit. The answer in <a href="https://stackoverflow.com/questions/23070298/get-nested-json-object-with-gson-using-retrofit">Get nested JSON object with GSON using retrofit</a> is close to what I need, but doesn't handle <code>List</code>s. I've copied the generic version of the answer here:</p>
  
  <pre><code>public class RestDeserializer&lt;T&gt; implements JsonDeserializer&lt;T&gt; {
    private Class&lt;T&gt; mClass;
    private String mKey;
  
    public RestDeserializer(Class&lt;T&gt; targetClass, String key) {
      mClass = targetClass;
      mKey = key;
    }
  
    @Override
    public T deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext)
      throws JsonParseException {
  
      JsonElement value = jsonElement.getAsJsonObject().get(mKey);
      if (value != null) {
        return new Gson().fromJson(value, mClass);
      } else {
        return new Gson().fromJson(jsonElement, mClass);
      }
    }
  }
  </code></pre>
  
  <p>My goal is to have this call "just work".</p>
  
  <pre><code>@GET("/api/v1/protected/devices")
  public void getDevices(Callback&lt;List&lt;Device&gt;&gt; callback);
  </code></pre>