title: Gson: Is there an easier way to serialize a map
body: <p><a href="http://code.google.com/p/google-gson/issues/detail?id=45">This</a> link from the Gson project seems to indicate that I would have to do something like the following for serializing a typed Map to JSON:</p>
  
  <pre><code>    public static class NumberTypeAdapter 
        implements JsonSerializer&lt;Number&gt;, JsonDeserializer&lt;Number&gt;,
  InstanceCreator&lt;Number&gt; {
  
      public JsonElement serialize(Number src, Type typeOfSrc, JsonSerializationContext
  context) {
        return new JsonPrimitive(src);
      }
  
      public Number deserialize(JsonElement json, Type typeOfT,
  JsonDeserializationContext context)
          throws JsonParseException {
        JsonPrimitive jsonPrimitive = json.getAsJsonPrimitive();
        if (jsonPrimitive.isNumber()) {
          return jsonPrimitive.getAsNumber();
        } else {
          throw new IllegalStateException("Expected a number field, but was " + json);
        }
      }
  
      public Number createInstance(Type type) {
        return 1L;
      }
    }
  
    public static void main(String[] args) {
      Map&lt;String, Number&gt; map = new HashMap&lt;String, Number&gt;();    
      map.put("int", 123);
      map.put("long", 1234567890123456789L);
      map.put("double", 1234.5678D);
      map.put("float", 1.2345F);
      Type mapType = new TypeToken&lt;Map&lt;String, Number&gt;&gt;() {}.getType();
  
      Gson gson = new GsonBuilder().registerTypeAdapter(Number.class, new
  NumberTypeAdapter()).create();
      String json = gson.toJson(map, mapType);
      System.out.println(json);
  
      Map&lt;String, Number&gt; deserializedMap = gson.fromJson(json, mapType);
      System.out.println(deserializedMap);
    }
  </code></pre>
  
  <p>Cool and that works, but it seems like so much overhead (<strong><em>a whole Type Adapter class?</em></strong>). I have used other JSON libraries like JSONLib and they let you build a map in the following way:</p>
  
  <pre><code>JSONObject json = new JSONObject();
  for(Entry&lt;String,Integer&gt; entry : map.entrySet()){
       json.put(entry.getKey(), entry.getValue());
  }
  </code></pre>
  
  <p>Or if I have a custom class something like the following:</p>
  
  <pre><code>JSONObject json = new JSONObject();
  for(Entry&lt;String,MyClass&gt; entry : map.entrySet()){
   JSONObject myClassJson =  JSONObject.fromObject(entry.getValue());
       json.put(entry.getKey(), myClassJson);
  }
  </code></pre>
  
  <p>The process is more manual, but requires way less code and doesn't have the overhead of haivng to create a custom Type Adapter for Number or in most cases <strong><em>for my own custom class</em></strong>.</p>
  
  <p>Is this the only way to serialize a map with Gson, or has anyone found a way that beats out what Gson recommends in the link above.</p>