com.fasterxml.jackson.databind.JsonNode.at()方法的使用及代码示例

x33g5p2x  于2022-01-21 转载在 其他  
字(12.1k)|赞(0)|评价(0)|浏览(740)

本文整理了Java中com.fasterxml.jackson.databind.JsonNode.at()方法的一些代码示例,展示了JsonNode.at()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。JsonNode.at()方法的具体详情如下:
包路径:com.fasterxml.jackson.databind.JsonNode
类名称:JsonNode
方法名:at

JsonNode.at介绍

[英]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 #isMissingNode() returns true.
[中]用于定位给定JSON指针实例指定的节点的方法。方法将永远不会返回null;如果不存在匹配节点,则将返回一个节点,其中#isMissingNode()返回true。

代码示例

代码示例来源:origin: Vedenin/useful-java-links

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!"
}

代码示例来源:origin: redisson/redisson

/**
 * 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));
}

代码示例来源:origin: testcontainers/testcontainers-java

@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;
      }
    });
}

代码示例来源:origin: testcontainers/testcontainers-java

.withRegistryAddress(helperResponse.at("/ServerURL").asText())
.withUsername(helperResponse.at("/Username").asText())
.withPassword(helperResponse.at("/Secret").asText());

代码示例来源:origin: redisson/redisson

/**
 * 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());
}

代码示例来源:origin: stackoverflow.com

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

代码示例来源:origin: palantir/atlasdb

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;
}

代码示例来源:origin: briandilley/jsonrpc4j

@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);
}

代码示例来源:origin: briandilley/jsonrpc4j

@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);
}

代码示例来源:origin: briandilley/jsonrpc4j

@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);
}

代码示例来源:origin: briandilley/jsonrpc4j

"  \"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);

代码示例来源:origin: puppetlabs/europa

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";
}

代码示例来源:origin: Erudika/para

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();
}

代码示例来源:origin: com.linecorp.centraldogma/centraldogma-common-shaded

JsonNode ensureExistence(JsonNode node) {
  final JsonNode found = node.at(path);
  if (found.isMissingNode()) {
    throw new JsonPatchException("non-existent path: " + path);
  }
  return found;
}

代码示例来源:origin: com.reprezen.jsonoverlay/jsonoverlay

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;
}

代码示例来源:origin: jurmous/etcd4j

@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);
}

代码示例来源:origin: otto-de/edison-microservice

@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"))
  );
}

代码示例来源:origin: otto-de/edison-microservice

@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"))
  );
}

代码示例来源:origin: jurmous/etcd4j

@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);
}

代码示例来源:origin: otto-de/edison-microservice

@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"))
  );
}

相关文章