title: How to fix 'JsonNull cannot be cast to JsonObject'
body: <p>I call a post API which responds with details on specific addresses, however some of the responses that get returned have no data so they'll be returned as null. How do I stop the casting error in my code? </p>
  
  <p>I currently only get the data as a Json Object and I'm not sure how to rework my code that so when a JsonNull Element gets returned I can handle that data. </p>
  
  <pre><code>JsonElement element = new JsonParser().parse(jsonString);
  JsonObject jsonObject = element.getAsJsonObject();
  jsonObject = jsonObject.getAsJsonObject("response"); // This is either an object or it is null 
  
  String buildName = jsonObject.get("buildingName").getAsString();
  String buildNum = jsonObject.get("premisesNumber").getAsString();
  String streetName = jsonObject.get("streetName").getAsString();
  </code></pre>
  
  <p>What I expect to be returned would be either the address details for valid addresses or no information at all for the invalid addresses.</p>
  
  <p>The error that gets produced is this: 
  java.lang.ClassCastException: com.google.gson.JsonNull cannot be cast to com.google.gson.JsonObject</p>