Gets a number from an object for the given key. If the key is not present, this returns null. If the value does not represent a float, throws an exception.
(Map<String, ?> obj, String key)
| 126 | * If the value does not represent a float, throws an exception. |
| 127 | */ |
| 128 | @Nullable |
| 129 | public static Float getNumberAsFloat(Map<String, ?> obj, String key) { |
| 130 | assert key != null; |
| 131 | if (!obj.containsKey(key)) { |
| 132 | return null; |
| 133 | } |
| 134 | Object value = obj.get(key); |
| 135 | if (value instanceof Float) { |
| 136 | return (Float) value; |
| 137 | } |
| 138 | if (value instanceof String) { |
| 139 | try { |
| 140 | return Float.parseFloat((String) value); |
| 141 | } catch (NumberFormatException e) { |
| 142 | throw new IllegalArgumentException( |
| 143 | String.format("string value '%s' for key '%s' cannot be parsed as a float", value, |
| 144 | key)); |
| 145 | } |
| 146 | } |
| 147 | throw new IllegalArgumentException( |
| 148 | String.format("value %s for key '%s' is not a float", value, key)); |
| 149 | } |
| 150 | |
| 151 | /** |
| 152 | * Gets a number from an object for the given key, casted to an integer. If the key is not |