public Optional<Integer> maybeGetInt(int index) { return maybeGet(index).map(e -> e.asInt()); }
default Optional<Integer> maybeGetInt(String...labels) { return maybeGet(labels).map(e -> e.asInt()); }
/** * @param field * name of the field * @param defaultValue * default value that is returned if the field has no value * @return value of the field as an int */ default int get(@Nonnull String field, int defaultValue) { JsonElement e = get(field); if (e == null) { return defaultValue; } else { return e.asInt(); } }
default Optional<Integer> maybeGetInt(String...labels) { return getJsonObject().maybeGet(labels).map(e -> e.asInt()); }
/** * Get a value at a particular path in an object structure. * * @param labels * one or more text labels * @return value or null if it doesn't exist at the specified path */ default Integer getInt(String... labels) { JsonElement jsonElement = get(labels); if (jsonElement == null || jsonElement.isNull()) { return null; } else { return jsonElement.asInt(); } }
public void shouldParseStringWhenNeeded() { JsonElement e = new JsonPrimitive("42"); // a string assertThat(e.asInt()).isEqualTo(42); assertThat(e.asFloat()).isEqualTo(42.0f); assertThat(e.asString()).isEqualTo("42"); assertThat(e.asNumber().toString()).isEqualTo("42"); } }
/** * @param field * name of the field * @param defaultValue * default value that is returned if the field has no value * @return value of the field as a boolean */ default boolean get(@Nonnull String field, boolean defaultValue) { JsonElement e = get(field); if (e == null) { return defaultValue; } else { if (e.isBoolean()) { return e.asBoolean(); } else if (e.isNumber()) { return e.asInt() > 0; } else if (e.isPrimitive()) { return Boolean.valueOf(e.asString()); } else { throw new JsonTypeMismatchException("expected primitive value but was " + e.type()); } } }
public void shouldIterateOverArrays() { JsonArray twodarray = array(); twodarray.add(array(42,42)); for(JsonArray arr: twodarray.arrays()) { assertThat(arr.get(0).asInt(), is(42)); } }
/** * Get a value at a particular path in an object structure. * * @param labels * one or more text labels * @return value or null if it doesn't exist at the specified path */ default Boolean getBoolean(final String... labels) { JsonElement jsonElement = get(labels); if (jsonElement == null || jsonElement.isNull()) { return null; } else { if (jsonElement.isBoolean()) { return jsonElement.asBoolean(); } else if (jsonElement.isNumber()) { return jsonElement.asInt() > 0; } else if (jsonElement.isPrimitive()) { return Boolean.valueOf(jsonElement.asString()); } else { throw new JsonTypeMismatchException("expected primitive value but was " + jsonElement.type()); } } }