title: How to deserialize json with optional fields using Gson
body: <p>I'm using Gson to deserialize a JSON string from a given API using the following Code.</p>
  
  <pre><code>Gson gson = new Gson();
  Map&lt;String, CustomDto&gt; test = gson.fromJson(result, new TypeToken&lt;Map&lt;String, CustomDto&gt;&gt;() {}.getType());
  </code></pre>
  
  <p>The <code>CustomDto</code> is an object constructed from primitives (int, long, boolean) and another Object. The problem I run into is that this Object is optional. Sometimes it gets transmitted, sometimes it is just not there. I was expecting if a field is missing in the JSON string that the associated set method should not be called (like in Jackson) and it should just work unfortunate that is not the case and i run into an exception:  </p>
  
  <pre><code>Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 207 column 23
  </code></pre>
  
  <p>If I remove the field from the <code>CustomDto</code>, it just works fine but then there is the problem if it will get transmitted. May I ask is there some annotation to flag fields optional in the entity class or can someone give me some advice how to handle this?</p>
  
  <p>Thanks everyone.</p>