title: GSON Case-Insensitive Enum Deserialization
body: <p>I have an enum:</p>
  
  <pre class="lang-java prettyprint-override"><code>enum Type {
      LIVE, UPCOMING, REPLAY
  }
  
  </code></pre>
  
  <p>And some JSON:</p>
  
  <pre><code>{
      "type": "live"
  }
  </code></pre>
  
  <p>And a class:</p>
  
  <pre class="lang-java prettyprint-override"><code>class Event {
      Type type;
  }
  </code></pre>
  
  <p>When I try to deserialize the JSON, using GSON, I receive <code>null</code> for the <code>Event</code> type field, since the case of the type field in the JSON does not match that of the enum.</p>
  
  <pre class="lang-java prettyprint-override"><code>Events events = new Gson().fromJson(json, Event.class);
  </code></pre>
  
  <p>If I change the enum to the following, then all works fine:</p>
  
  <pre class="lang-java prettyprint-override"><code>enum Type {
      live, upcoming, replay
  }
  </code></pre>
  
  <p>However, I would like to leave the enum constants as all uppercase.</p>
  
  <p>I'm assuming I need to write an adapter but haven't found any good documentation or examples.  </p>
  
  <p>What is the best solution?  </p>
  
  <hr>
  
  <p><strong>Edit:</strong></p>
  
  <p>I was able to get a JsonDeserializer working.  Is there a more generic way to write this though, as it would be unfortunate to have to write this each time there is a case mismatch between enum values and JSON strings.</p>
  
  <pre class="lang-java prettyprint-override"><code>protected static class TypeCaseInsensitiveEnumAdapter implements JsonDeserializer&lt;Type&gt; {
      @Override
      public Type deserialize(JsonElement json, java.lang.reflect.Type classOfT, JsonDeserializationContext context)
              throws JsonParseException {         
          return Type.valueOf(json.getAsString().toUpperCase());
      }
  }
  </code></pre>