JSONUtils { public static int getInt(JSONObject obj, String field) throws JSONException { if (obj == null || StringUtils.isEmpty(field)) { return 0; } Object object = obj.get(field); try { return object instanceof Number ? ((Number) object).intValue() : Integer.parseInt((String) object); } catch (Exception e) { throw new JSONException("JSONObject[" + field + "] is not an int."); } }  static String getString(JSONObject obj, String field); static int getInt(JSONObject obj, String field); static long getLong(JSONObject obj, String field); static long getLong(JSONObject obj, String field, long defaultValue); static Boolean getBoolean(JSONObject obj, String field); static JSONObject getJSONObject(JSONObject obj, String field); static JSONArray getJSONArray(JSONObject obj, String field);  }
@Test public void testGetInt() throws ParseException { JSONParser parser = new JSONParser(); JSONObject jsonObject = (JSONObject) parser.parse("{\"salary\":\"2000\",\"isYhd\":\"false\"}"); Assert.assertEquals(2000, JSONUtils.getInt(jsonObject, "salary")); }
@Test public void testGetInt1() throws ParseException { thrown.expect(org.json.JSONException.class); JSONParser parser = new JSONParser(); JSONObject jsonObject = (JSONObject) parser.parse("{\"salary\":\"xxx\",\"isYhd\":\"false\"}"); Assert.assertEquals(2000, JSONUtils.getInt(jsonObject, "salary")); }