title: How to handle optional keys in JSON response with Java
body: <pre><code>"app":{  
    "icon":{  
       "icon":"TOP_RATED"
    },
    "message":{  
       "_type":"TextSpan",
       "text":"Top Rated"
    }
  }
  </code></pre>
  
  <p>I keep seeing the following code in one of the projects that I have inherited. The JSON response above is parsed as follows</p>
  
  <pre><code>// itemObject has the entire json response
  // appObject is a POJO with icon, type fields
  String icon= JsonPath.with(itemObject).getAsString("icon/icon");
  appObject.setIcon(icon);
  
  String type = "";
  try {
    type = JsonPath.with(itemObject).getAsString("message/_type");
  catch(IllegalArgumentException e) {
    // do nothing if type is not found in response
  } finally {
      // set type to empty string if it's not found
      appObject.setType(type);
  }
  </code></pre>
  
  <p>In the scenario, when _type doesn't exist for a specific app, would it be best to surround it with a try/catch block as shown above? It just seems wrong to use try/catch/finally block to process business logic instead of error handling. What is a better way to do the same and can Java 8 Optional help with this? </p>