JsonPredicate implements JsonSerializable, Predicate<JsonSerializable> { @NonNull public static JsonPredicate parse(@Nullable JsonValue jsonValue) throws JsonException { if (jsonValue == null || !jsonValue.isJsonMap() || jsonValue.optMap().isEmpty()) { throw new JsonException("Unable to parse empty JsonValue: " + jsonValue); } JsonMap map = jsonValue.optMap(); JsonPredicate.Builder builder = JsonPredicate.newBuilder(); String type = getPredicateType(map); if (type != null) { builder.setPredicateType(type); for (JsonValue child : map.opt(type).optList()) { if (!child.isJsonMap()) { continue; } if (getPredicateType(child.optMap()) != null) { builder.addPredicate(parse(child)); continue; } builder.addMatcher(JsonMatcher.parse(child)); } } else { builder.addMatcher(JsonMatcher.parse(jsonValue)); } try { return builder.build(); } catch (IllegalArgumentException e) { throw new JsonException("Unable to parse JsonPredicate.", e); } } private  JsonPredicate(Builder builder); @NonNull static Builder newBuilder(); @NonNull @Override JsonValue toJsonValue(); @NonNull static JsonPredicate parse(@Nullable JsonValue jsonValue); @Override boolean apply(@Nullable JsonSerializable value); @Override boolean equals(@Nullable Object o); @Override int hashCode(); @NonNull
    static final String OR_PREDICATE_TYPE; @NonNull
    static final String AND_PREDICATE_TYPE; @NonNull
    static final String NOT_PREDICATE_TYPE; }
@Test public void testParse() throws JsonException { JsonPredicate andOr = JsonPredicate.newBuilder() .setPredicateType(JsonPredicate.AND_PREDICATE_TYPE) .addMatcher(JsonMatcher.newBuilder() .setKey("head") .setValueMatcher(ValueMatcher.newNumberRangeMatcher(0.0, 2.0)) .build()) .addMatcher(JsonMatcher.newBuilder() .setKey("ears") .setValueMatcher(ValueMatcher.newValueMatcher(JsonValue.wrap(2))) .build()) .build(); JsonPredicate notOr = JsonPredicate.newBuilder() .setPredicateType(JsonPredicate.OR_PREDICATE_TYPE) .addMatcher(JsonMatcher.newBuilder() .setKey("tail") .setValueMatcher(ValueMatcher.newNumberRangeMatcher(0.0, 2.0)) .build()) .addPredicate(andOr) .build(); JsonPredicate not = JsonPredicate.newBuilder() .setPredicateType(JsonPredicate.NOT_PREDICATE_TYPE) .addPredicate(notOr) .build(); JsonPredicate or = JsonPredicate.newBuilder() .setPredicateType(JsonPredicate.OR_PREDICATE_TYPE) .addMatcher(legMatcher) .addMatcher(weightMatcher) .addPredicate(not) .build(); JsonPredicate predicate = JsonPredicate.newBuilder() .setPredicateType(JsonPredicate.AND_PREDICATE_TYPE) .addMatcher(nameMatcher) .addMatcher(sleepMatcher) .addPredicate(or) .build(); assertEquals(predicate, JsonPredicate.parse(predicate.toJsonValue())); }
@Test(expected = JsonException.class) public void testParseInvalidJson() throws JsonException { JsonPredicate.parse(JsonValue.wrap("not valid")); }