Refine search
/** * {@inheritDoc} */ public JsonAsserter assertNotDefined(String path) { try { Configuration c = Configuration.defaultConfiguration(); JsonPath.using(c).parse(jsonObject).read(path); throw new AssertionError(format("Document contains the path <%s> but was expected not to.", path)); } catch (PathNotFoundException e) { } return this; }
private static void maskList(DocumentContext ctx, String jsonPath, String expression) { ctx.configuration().addOptions(Option.AS_PATH_LIST); Configuration conf = Configuration.builder().options(Option.AS_PATH_LIST).build(); DocumentContext context = JsonPath.using(conf).parse(ctx.jsonString()); List<String> pathList = context.read(jsonPath); /** * when reach here, ctx.read(jsonPath) should only give us a list of strings so that we can replace with MASK_REPLACEMENT_CHAR * list of values can belongs to a same path or different paths, we should treat differently. * two situations: * an array contains multiple String values like: "list": ["ab", "cd", "ef] * or single value belongs to different paths. */ if(pathList != null && pathList.size() == 1) { String path = pathList.get(0); List values = ctx.read(path); JSONArray maskedValue = new JSONArray(); //mask each value in the list of the same path values.forEach(o -> maskedValue.add(replaceWithMask(o.toString(), MASK_REPLACEMENT_CHAR.charAt(0), expression))); ctx.set(path, maskedValue); } else { for (String path : Optional.ofNullable(pathList).orElse(Collections.emptyList())) { Object value = ctx.read(path); ctx.set(path, replaceWithMask(value.toString(), MASK_REPLACEMENT_CHAR.charAt(0), expression)); } } }
@Test(expected = InvalidModificationException.class) public void rootCannotBeMapped(){ MapFunction mapFunction = new MapFunction() { @Override public Object map(Object currentValue, Configuration configuration) { return currentValue.toString()+"converted"; } }; Object o = parse(JSON_DOCUMENT).map("$", mapFunction).json(); }
private static void applyMask(Map.Entry<String, JsonNode> entry, DocumentContext ctx) { Object value; String jsonPath = entry.getKey(); try { value = ctx.read(jsonPath); if (!(value instanceof String || value instanceof Integer || value instanceof List<?>)) { logger.error("The value specified by path {} cannot be masked", jsonPath); } else { if (!(value instanceof List<?>)) { ctx.set(jsonPath, replaceWithMask(value.toString(), MASK_REPLACEMENT_CHAR.charAt(0), entry.getValue().asText())); } else if(value instanceof List<?>){ for(Object ele : (List)value) { if(!(ele instanceof String)) { logger.error("json path: {} is incorrect, cannot mask an object", jsonPath); return; } } maskList(ctx, jsonPath, entry.getValue().asText()); } } } catch (PathNotFoundException e) { logger.warn("JsonPath {} could not be found.", jsonPath); } } private static void maskList(DocumentContext ctx, String jsonPath, String expression) {
/** * Variant of {@link #evaluateJsonPath(String)} with a target type. * This can be useful for matching numbers reliably for example coercing an * integer into a double. * @param content the content to evaluate against * @return the result of the evaluation * @throws AssertionError if the evaluation fails */ public Object evaluateJsonPath(String content, Class<?> targetType) { try { return JsonPath.parse(content).read(this.expression, targetType); } catch (Throwable ex) { String message = "No value at JSON path \"" + this.expression + "\""; throw new AssertionError(message, ex); } }
@Test public void combine_filter_deep_criteria() { String json = "[\n" + " {\n" + " \"first-name\" : \"John\",\n" + " \"last-name\" : \"Irving\",\n" + " \"address\" : {\"state\" : \"Texas\"}\n" + " },\n" + " {\n" + " \"first-name\" : \"Jock\",\n" + " \"last-name\" : \"Ewing\",\n" + " \"address\" : {\"state\" : \"Texas\"}\n" + " },\n" + " {\n" + " \"first-name\" : \"Jock\",\n" + " \"last-name\" : \"Barnes\",\n" + " \"address\" : {\"state\" : \"Nevada\"}\n" + " } \n" + "]"; Filter filter = filter( where("first-name").is("Jock") .and("address.state").is("Texas")); List<Map<String, Object>> jocksInTexas1 = JsonPath.read(json, "$[?]", filter); List<Map<String, Object>> jocksInTexas2 = JsonPath.read(json, "$[?(@.first-name == 'Jock' && @.address.state == 'Texas')]"); JsonPath.parse(json).json(); assertThat((String)JsonPath.read(jocksInTexas1, "$[0].address.state"), is("Texas")); assertThat((String)JsonPath.read(jocksInTexas1, "$[0].first-name"), is("Jock")); assertThat((String)JsonPath.read(jocksInTexas1, "$[0].last-name"), is("Ewing")); }
@Test public void issue_143() { String json = "{ \"foo\": { \"bar\" : \"val\" }, \"moo\": { \"cow\" : \"val\" } }"; Configuration configuration = Configuration.builder().options( Option.AS_PATH_LIST ).build(); List<String> pathList = JsonPath.using(configuration).parse(json).read(JsonPath.compile("$.*.bar")); assertThat(pathList).containsExactly("$['foo']['bar']"); }
@Test public void issue_171() { String json = "{\n" + " \"can delete\": \"this\",\n" + " \"can't delete\": \"this\"\n" + "}"; DocumentContext context = using(JACKSON_JSON_NODE_CONFIGURATION).parse(json); context.set("$.['can delete']", null); context.set("$.['can\\'t delete']", null); ObjectNode objectNode = context.read("$"); assertThat(objectNode.get("can delete").isNull()); assertThat(objectNode.get("can't delete").isNull()); }
/** * Creates a JSONAsserter * * @param json the JSON document to create a JSONAsserter for * @return a JSON asserter initialized with the provided document * @throws ParseException when the given JSON could not be parsed */ public static JsonAsserter with(String json) { return new JsonAsserterImpl(JsonPath.parse(json).json()); }
@Test public void json_can_be_fetched_as_string() { String expected = "{\"category\":\"reference\",\"author\":\"Nigel Rees\",\"title\":\"Sayings of the Century\",\"display-price\":8.95}"; String jsonString1 = using(JSON_SMART_CONFIGURATION).parse(JSON_BOOK_DOCUMENT).jsonString(); String jsonString2 = using(JACKSON_CONFIGURATION).parse(JSON_BOOK_DOCUMENT).jsonString(); String jsonString3 = using(JACKSON_JSON_NODE_CONFIGURATION).parse(JSON_BOOK_DOCUMENT).jsonString(); String jsonString4 = using(GSON_CONFIGURATION).parse(JSON_BOOK_DOCUMENT).jsonString(); Assertions.assertThat(jsonString1).isEqualTo(expected); Assertions.assertThat(jsonString2).isEqualTo(expected); Assertions.assertThat(jsonString3).isEqualTo(expected); Assertions.assertThat(jsonString4).isEqualTo(expected); }