title: Deserialize into dynamic Java types
body: <p>My problem today is that I have this kind of JSON,
  with an array of objects, each object having
  two properties: <code>type</code> and <code>value</code>.</p>
  
  <pre class="lang-js prettyprint-override"><code>[{
      "type": "Boolean",
      "value": false
  }, {
      "type": "String[]",
      "value": ["one", "two", "three"]
  }]
  </code></pre>
  
  <p>As you see, the <code>value</code> class depends on the <code>type</code>.
  I may have a <code>type: MyClass</code>, with <code>value</code> being a complex object.</p>
  
  <p>I want to be able to deserialize this array (and serialize it back
  into JSON afterwards).</p>
  
  <p>I started looking into the <a href="https://github.com/google/gson" rel="nofollow noreferrer">Gson</a> library, but I may change anytime.
  From what I've read, there is only one way I know of:</p>
  
  <pre class="lang-java prettyprint-override"><code>public class MyExtractor implements JsonDeserializer&lt;Object&gt; {
      @Override
      public Object deserialize(JsonElement elem, Type jtype,
              JsonDeserializationContext jdc) throws JsonParseException {
          // elem is an object
          JsonObject obj = elem.getAsJsonObject();
          String type = obj.get("type").getAsString();
          // Return a different kind of Object depending on the 'type' attr
          switch (type) {
          case "Boolean":
              Boolean bool = obj.get("value").getAsBoolean();
              return bool;
          case "String[]":
              JsonArray data = obj.get("value").getAsJsonArray();
              List&lt;String&gt; list = new ArrayList&lt;String&gt;();
              for (JsonElement item : data) {
                  list.add(item.getAsString());
              }
              return list;
          }
      }
  }
  </code></pre>
  
  <p>And here I add code to associate each <code>type</code> to its proper class.
  This will probably work as I want, but is there a better way?
  This one ends up requiring quite a lot of template.</p>
  
  <p>Also, the deserialized items are cast into <code>Object</code> so I don't
  have access to their methods without reading their <code>getClass()</code> and
  casting them back, and I can't benefit from <a href="https://en.wikipedia.org/wiki/Function_overloading" rel="nofollow noreferrer">overloading</a>.</p>
  
  <p>Are there libraries with different approaches to the problem?</p>