title: Custom Java map deserialzer in Gson
body: <p>Is it possible to convert an array of object pairs into a <code>Map</code>, by selecting values from each pair, without creating an intermediate POJO?</p>
  
  <p>For example, say that there are 2 <code>Java</code> classes (<code>Key.class</code>, <code>Value.class</code>) and a <code>JSON</code> array constructed from serialized pairs of their objects, as follows</p>
  
  <pre><code>[
    {"key":{}, "value":{}}, // Objects k1, v1
    {"key":{}, "value":{}}, // Objects k2, v2
    {"key":{}, "value":{}}, // Objects k3, v3
    {"key":{}, "value":{}}, // Objects k4, v4
  ]
  </code></pre>
  
  <p>Can <code>Gson</code> "directly" (i.e., without a POJO definition) deserialize the above array into a <code>Map</code>, in which the actual keys and values are populated from a manipulation of the corresponding <code>Key</code> and <code>Value</code> objects, instead of the "full" objects?</p>
  
  <p>In other words, given two <code>Java</code> types <code>K</code> and <code>V</code> that may be different to <code>Key</code> and <code>Value</code>, the deserialization per pair should be</p>
  
  <pre><code>(k1:Key, v1:Value) --&gt; (k1':K, v1':V)
  </code></pre>
  
  <p>where</p>
  
  <pre><code>k1' = function(k1)
  v1' = function(v1)
  </code></pre>
  
  <p>A custom adapter like this does not work:</p>
  
  <pre><code>GsonBuilder builder = new GsonBuilder();
  Type type = (new TypeToken&lt;Map&lt;K, V&gt;&gt;() {}).getType();    
  builder.registerTypeAdapter(type, new JsonDeserializer&lt;Map&lt;Key, Value&gt;&gt;() {
    @Override
    public Map&lt;K, V&gt; deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException {
      // Custom deserialization block,
      // invoking the `function()` method
    }
  Gson gson = builder.create();
  </code></pre>
  
  <p>Using the above adapter results in <code>Gson</code> passing the entire array to the <code>deserialize()</code> method, where it has to be manipulated manually, which is both tedious and error-prone.</p>
  
  <p>With a custom <code>POJO</code> like</p>
  
  <pre><code>public class KeyValue {
    Key k;
    Value v;
  }
  </code></pre>
  
  <p>the above <code>JSON</code> array can be deserialized into an array or set of <code>KeyValue</code> objects, which can then be converted to a <code>Map&lt;K, V&gt;</code>. But could the same be done without the <code>KeyValue</code> POJO;</p>