JsonHelper { public <T> T getKeyValue(JSONObject jsonObject, Object key, Class<T> classType) { Object result = jsonObject.get(key); if (result == null) { throw new IllegalArgumentException(String.format("Failed to get \"%s\" key value from JSON object.", key.toString())); } try { return classType.cast(result); } catch (ClassCastException e) { throw new IllegalArgumentException(String.format("Failed to cast \"%s\" key value to %s.", result.toString(), classType.getName()), e); } }  T getKeyValue(JSONObject jsonObject, Object key, Class<T> classType); String objectToJson(Object object); List<T> unmarshallJsonToListOfObjects(Class<T> classType, String jsonContent); T unmarshallJsonToObject(Class<T> classType, String jsonContent);  }
@Test public void testGetKeyValue() throws Exception { JSONParser jsonParser = new JSONParser(); JSONObject jsonObject = (JSONObject) jsonParser.parse(String.format("{\"%s\" : \"%s\"}", KEY, VALUE)); assertEquals(VALUE, jsonHelper.getKeyValue(jsonObject, KEY, String.class)); try { jsonHelper.getKeyValue(jsonObject, I_DO_NOT_EXIST, String.class); fail(); } catch (IllegalArgumentException e) { assertEquals(String.format("Failed to get \"%s\" key value from JSON object.", I_DO_NOT_EXIST), e.getMessage()); } try { jsonHelper.getKeyValue(jsonObject, KEY, BigDecimal.class); fail(); } catch (IllegalArgumentException e) { assertEquals(String.format("Failed to cast \"%s\" key value to %s.", VALUE, BigDecimal.class.getName()), e.getMessage()); } }