public static void main(String[] args) throws IOException { ObjectMapper mapper = new ObjectMapper(); JsonNode root = mapper.readTree(json); String author = root.at("/store/book/3/title").asText(); System.out.println(author); // print ["Hello, Middle-earth! "] System.out.println(); String jsonHiWorld = "{\"message\":\"Hi\",\"place\":{\"name\":\"World!\"}}\""; String message = mapper.readTree(jsonHiWorld).at("/message").asText(); String place = mapper.readTree(jsonHiWorld).at("/place/name").asText(); System.out.println(message + " " + place); // print "Hi World!" }
/** * Convenience method that is functionally equivalent to: *<pre> * return at(JsonPointer.valueOf(jsonPointerExpression)); *</pre> *<p> * Note that if the same expression is used often, it is preferable to construct * {@link JsonPointer} instance once and reuse it: this method will not perform * any caching of compiled expressions. * * @param jsonPtrExpr Expression to compile as a {@link JsonPointer} * instance * * @return Node that matches given JSON Pointer: if no match exists, * will return a node for which {@link TreeNode#isMissingNode()} returns true. * * @since 2.3 */ @Override public final JsonNode at(String jsonPtrExpr) { return at(JsonPointer.compile(jsonPtrExpr)); }
@NotNull private HttpWaitStrategy createNodeWaitStrategy() { return new HttpWaitStrategy() .forPath("/pools/default/") .withBasicCredentials(clusterUsername, clusterPassword) .forStatusCode(HTTP_OK) .forResponsePredicate(response -> { try { return Optional.of(MAPPER.readTree(response)) .map(n -> n.at("/nodes/0/status")) .map(JsonNode::asText) .map("healthy"::equals) .orElse(false); } catch (IOException e) { logger().error("Unable to parse response {}", response); return false; } }); }
/** * Method for locating node specified by given JSON pointer instances. * Method will never return null; if no matching node exists, * will return a node for which {@link #isMissingNode()} returns true. * * @return Node that matches given JSON Pointer: if no match exists, * will return a node for which {@link #isMissingNode()} returns true. * * @since 2.3 */ @Override public final JsonNode at(JsonPointer ptr) { // Basically: value nodes only match if we have "empty" path left if (ptr.matches()) { return this; } JsonNode n = _at(ptr); if (n == null) { return MissingNode.getInstance(); } return n.at(ptr.tail()); }
JsonNode root = mapper.readTree(src); int zip =root.at("/address/zip").asIntValue(); double height = root.add("/dimensions/1").asDoubleValue();// assuming it's the second number in there
private static JsonNode findRoot(JsonNode node, @Nullable String configRoot) { if (Strings.isNullOrEmpty(configRoot)) { return node; } JsonNode root = node.at(JsonPointer.valueOf(configRoot)); if (root.isMissingNode()) { return null; } return root; }
@Test public void interceptorsPostHandleJsonExceptionTest() throws IOException { final String requestGood = "{\n" + " \"id\": 0,\n" + " \"jsonrpc\": \"2.0\",\n" + " \"method\": \"testMethod\",\n" + " \"params\": [\"test.cool\"]\n" + " }\n" + "}"; String exceptionMessage = "123"; String returnString = "test"; String responseError = "{\"jsonrpc\":\"2.0\",\"id\":0,\"error\":{\"code\":-32001,\"message\":\"" + exceptionMessage + "\",\"data\":{\"exceptionTypeName\":\"java.lang.RuntimeException\",\"message\":\"" + exceptionMessage + "\"}}}"; // expect(mockService.testMethod(mapper.readTree(requestGood).at("/params/0").asText())).andReturn(returnString); mockInterceptor.postHandleJson(anyObject(JsonNode.class)); expectLastCall().andThrow(new RuntimeException(exceptionMessage)); replay(mockService, mockInterceptor); jsonRpcServer.handleRequest(new ByteArrayInputStream(requestGood.getBytes(StandardCharsets.UTF_8)), byteArrayOutputStream); assertEquals(responseError, byteArrayOutputStream.toString("UTF-8").trim()); verify(mockService, mockInterceptor); }
@Test public void interceptorsPostHandleExceptionTest() throws IOException { final String requestGood = "{\n" + " \"id\": 0,\n" + " \"jsonrpc\": \"2.0\",\n" + " \"method\": \"testMethod\",\n" + " \"params\": [\"test.cool\"]\n" + " }\n" + "}"; String exceptionMessage = "123"; String returnString = "test"; String responseError = "{\"jsonrpc\":\"2.0\",\"id\":0,\"error\":{\"code\":-32001,\"message\":\"" + exceptionMessage + "\",\"data\":{\"exceptionTypeName\":\"java.lang.RuntimeException\",\"message\":\"" + exceptionMessage + "\"}}}"; // expect(mockService.testMethod(mapper.readTree(requestGood).at("/params/0").asText())).andReturn(returnString); mockInterceptor.postHandle( anyObject(), anyObject(Method.class), eq(new ArrayList<JsonNode>() {{ add(mapper.readTree(requestGood).at("/params/0")); }}), eq(new TextNode(returnString)) ); expectLastCall().andThrow(new RuntimeException(exceptionMessage)); replay(mockService, mockInterceptor); jsonRpcServer.handleRequest(new ByteArrayInputStream(requestGood.getBytes(StandardCharsets.UTF_8)), byteArrayOutputStream); assertEquals(responseError, byteArrayOutputStream.toString("UTF-8").trim()); verify(mockService, mockInterceptor); }
@Test public void interceptorsPreHandleExceptionTest() throws IOException { final String requestGood = "{\n" + " \"id\": 0,\n" + " \"jsonrpc\": \"2.0\",\n" + " \"method\": \"testMethod\",\n" + " \"params\": [\"test.cool\"]\n" + " }\n" + "}"; String exceptionMessage = "123"; String responseError = "{\"jsonrpc\":\"2.0\",\"id\":0,\"error\":{\"code\":-32001,\"message\":\"" + exceptionMessage + "\",\"data\":{\"exceptionTypeName\":\"java.lang.RuntimeException\",\"message\":\"" + exceptionMessage + "\"}}}"; // mockInterceptor.preHandle( anyObject(), anyObject(Method.class), eq(new ArrayList<JsonNode>() {{ add(mapper.readTree(requestGood).at("/params/0")); }}) ); expectLastCall().andThrow(new RuntimeException(exceptionMessage)); replay(mockInterceptor); jsonRpcServer.handleRequest(new ByteArrayInputStream(requestGood.getBytes(StandardCharsets.UTF_8)), byteArrayOutputStream); assertEquals(responseError, byteArrayOutputStream.toString("UTF-8").trim()); verify(mockInterceptor); }
" \"result\": \"test.ru\"}\n" + "}"; Iterator<JsonNode> paramsIterator = mapper.readTree(requestGood).at("/params").iterator(); List<JsonNode> paramsNodes = new ArrayList<>(); while (paramsIterator.hasNext()) { anyObject(Method.class), eq(paramsNodes), eq(mapper.readTree(responseGood).at("/result")) ); expectLastCall().times(1);
private String getContentType(JsonNode manifest, String contentType) { if ( null != contentType ) return contentType; JsonNode node = manifest.at("/mediaType"); if ( node.isTextual() ) return node.asText(); return "application/vnd.docker.distribution.manifest.v1+json"; }
private String getFullName(JsonNode profileNode) { JsonNode fNameNode = profileNode.at("/firstName/localized"); JsonNode lNameNode = profileNode.at("/lastName/localized"); String fName = fNameNode.elements().hasNext() ? fNameNode.elements().next().textValue() : ""; String lName = lNameNode.elements().hasNext() ? lNameNode.elements().next().textValue() : ""; return (fName + " " + lName).trim(); }
JsonNode ensureExistence(JsonNode node) { final JsonNode found = node.at(path); if (found.isMissingNode()) { throw new JsonPatchException("non-existent path: " + path); } return found; }
private <X> JsonOverlay<X> _addChild(String name, String path, OverlayFactory<X> factory) { JsonPointer pointer = JsonPointer.compile(path.isEmpty() ? "" : "/" + path); JsonNode childJson = json.at(pointer); JsonOverlay<X> child = factory.create(childJson, this, refMgr); child._setPathInParent(path); PropertyLocator locator = new PropertyLocator(name, path, json); childOrder.add(locator); children.put(name, child); return child; }
@Test public void testGetPartialJson() throws EtcdAuthenticationException, TimeoutException, EtcdException, IOException { JsonNode asJson = EtcdUtil.getAsJson("/etcd4j_test/widget", etcd); assertEquals(asJson.at("/debug").asText(), "on"); assertEquals(asJson.at("/window/name").asText(), "main_window"); assertEquals(asJson.at("/text/data").size(), 2); }
@Test public void shouldGetTeamInformation() throws IOException { when( internal_status_is_retrieved_as("application/json") ); then( assertThat(the_returned_json().at("/team/name").asText(), is("Test Team")), assertThat(the_returned_json().at("/team/technicalContact").asText(), is("technical@example.org")), assertThat(the_returned_json().at("/team/businessContact").asText(), is("business@example.org")) ); }
@Test public void shouldGetStatusWithDetails() throws IOException { when( internal_status_is_retrieved_as("application/json") ); then( assertThat(the_status_code().value(), is(200)), assertThat(the_returned_json().at("/application/status").asText(), is("WARNING")), assertThat(the_returned_json().at("/application/statusDetails/foo/status").asText(), is("OK")), assertThat(the_returned_json().at("/application/statusDetails/bar/status").asText(), is("WARNING")) ); }
@Test public void testAssignValueToObject() throws EtcdAuthenticationException, TimeoutException, EtcdException, IOException { String newJson = "{\n" + " \"test\":\"value\"\n" + "}"; JsonNode originalConfig = EtcdUtil.getAsJson("/etcd4j_test", etcd); assertEquals(originalConfig.at("/widget/window").has("test"), false); EtcdUtil.putAsJson("/etcd4j_test/widget/window", EtcdUtil.stringToJson(newJson), etcd); JsonNode updatedConfig = EtcdUtil.getAsJson("/etcd4j_test", etcd); assertEquals(updatedConfig.at("/widget/window").has("test"), true); }
@Test public void shouldGetStatusWithDependencies() throws IOException { when( internal_status_is_retrieved_as("application/json") ); then( assertThat(the_status_code().value(), is(200)), assertThat(the_returned_json().at("/dependencies/0/url").asText(), is("http://example.com/foo")) ); }