当前位置: 首页>>代码示例>>Java>>正文


Java JsonPath类代码示例

本文整理汇总了Java中com.jayway.jsonpath.JsonPath的典型用法代码示例。如果您正苦于以下问题:Java JsonPath类的具体用法?Java JsonPath怎么用?Java JsonPath使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


JsonPath类属于com.jayway.jsonpath包,在下文中一共展示了JsonPath类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: parse

import com.jayway.jsonpath.JsonPath; //导入依赖的package包/类
private List<DeviceData> parse(String topic, List<String> srcList) {
  List<DeviceData> result = new ArrayList<>(srcList.size());
  for (String src : srcList) {
    DocumentContext document = JsonPath.parse(src);
    long ts = System.currentTimeMillis();
    String deviceName;
    if (!StringUtils.isEmpty(deviceNameTopicExpression)) {
      deviceName = eval(topic);
    } else {
      deviceName = eval(document, deviceNameJsonExpression);
    }
    if (!StringUtils.isEmpty(deviceName)) {
      List<KvEntry> attrData = getKvEntries(document, attributes);
      List<TsKvEntry> tsData = getKvEntries(document, timeseries).stream().map(kv -> new BasicTsKvEntry(ts, kv))
          .collect(Collectors.toList());
      result.add(new DeviceData(deviceName, attrData, tsData, timeout));
    }
  }
  return result;
}
 
开发者ID:osswangxining,项目名称:iotgateway,代码行数:21,代码来源:MqttJsonConverter.java

示例2: getAnswer

import com.jayway.jsonpath.JsonPath; //导入依赖的package包/类
public static String getAnswer(RestTemplate restTemplate, String question) {
    String url = "http://www.tuling123.com/openapi/api";
    HttpHeaders headers = new HttpHeaders();
    headers.add("Ocp-Apim-Subscription-Key", "3f5a37d9698744f3b40c89e2f0c94fb1");
    headers.add("Content-Type", "application/x-www-form-urlencoded");


    MultiValueMap<String, String> bodyMap = new LinkedMultiValueMap<>();
    bodyMap.add("key", "e2e33efb4efb4e5794b48a18578384ee");
    bodyMap.add("info", question);


    HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(bodyMap, headers);
    String result = restTemplate.postForObject(url, requestEntity, String.class);
    return JsonPath.read(result, "$.text");
}
 
开发者ID:xjtushilei,项目名称:knowledge-forest-dialogue-recommendation,代码行数:17,代码来源:Tuling123.java

示例3: assertPaths

import com.jayway.jsonpath.JsonPath; //导入依赖的package包/类
private void assertPaths(JsonNode node, boolean shouldExist, String... paths) {
    Object document = Configuration.defaultConfiguration().jsonProvider().parse(node.toString());
    for (String path : paths) {
        try {
            Object object = JsonPath.read(document, path);
            if (isIndefinite(path)) {
                Collection c = (Collection) object;
                assertThat(c.isEmpty()).isNotEqualTo(shouldExist);
            } else if (!shouldExist) {
                Assert.fail("Expected path not to be found: " + path);
            }
        } catch (PathNotFoundException e) {
            if (shouldExist) {
                Assert.fail("Path not found: " + path);
            }
        }
    }
}
 
开发者ID:CSCfi,项目名称:exam,代码行数:19,代码来源:IntegrationTestCase.java

示例4: prepPath

import com.jayway.jsonpath.JsonPath; //导入依赖的package包/类
/**
 * Assemble an xpath using the given json path and json wrapper.
 *
 * @param jsonPath definite json path
 * @param wrapper object representation of QPP json
 * @return xpath that correlates to supplied json path
 */
public static String prepPath(String jsonPath, JsonWrapper wrapper) {
	String base = "$";
	String leaf = jsonPath;
	int lastIndex = jsonPath.lastIndexOf('.');
	JsonWrapper metaWrapper = new JsonWrapper(wrapper, false);

	if (lastIndex > 0) {
		base = jsonPath.substring(0, lastIndex);
		leaf = jsonPath.substring(lastIndex + 1);
	}

	JsonPath compiledPath = JsonPath.compile(base);
	Map<String, Object> jsonMap = compiledPath.read(metaWrapper.toString());

	Map<String, String> metaMap = getMetaMap(jsonMap, leaf);
	String preparedPath = "";
	if (metaMap != null) {
		preparedPath = makePath(metaMap, leaf);
	}
	return preparedPath;
}
 
开发者ID:CMSgov,项目名称:qpp-conversion-tool,代码行数:29,代码来源:PathCorrelator.java

示例5: evaluateJsonPathToString

import com.jayway.jsonpath.JsonPath; //导入依赖的package包/类
/**
 * Evaluates provided JSONPath expression into the {@link String}
 *
 * @param evalExpression Expression to evaluate
 * @param jsonSource JSON source
 * @return Evaluation result
 */
public static String evaluateJsonPathToString(String evalExpression,
                                              String jsonSource) {
    try {
        List<Object> parsedData =
                JsonPath.
                        using(Configuration.
                                defaultConfiguration().
                                addOptions(
                                        ALWAYS_RETURN_LIST,
                                        SUPPRESS_EXCEPTIONS)).
                        parse(jsonSource).
                        read(evalExpression);

        return collectionIsNotEmpty(parsedData) ?
                String.valueOf(
                        parsedData.
                                get(FIRST_ELEMENT)) :
                EMPTY;
    } catch (Exception e) {
        LOG.warning(COMMON_EVAL_ERROR_MESSAGE);
    }

    return EMPTY;
}
 
开发者ID:shimkiv,项目名称:trust-java,代码行数:32,代码来源:EvaluationUtils.java

示例6: assertIsValidJsonPath

import com.jayway.jsonpath.JsonPath; //导入依赖的package包/类
/**
 * Asserts that the string represents a valid JsonPath expression.
 *
 * @param path         Path expression to validate.
 * @param propertyName Name of property.
 */
public void assertIsValidJsonPath(String path, String propertyName) {
    if (path == null) {
        return;
    }
    if (path.isEmpty()) {
        problemReporter.report(new Problem(this, String.format("%s cannot be empty", propertyName)));
        return;
    }
    try {
        JsonPath.compile(path);
    } catch (InvalidPathException e) {
        problemReporter.report(new Problem(this,
                                           String.format("%s with value '%s' is not a valid JsonPath. %s", propertyName, path,
                                                         e.getMessage())));
    }
}
 
开发者ID:networknt,项目名称:light-workflow-4j,代码行数:23,代码来源:ValidationContext.java

示例7: assertJsonEquals

import com.jayway.jsonpath.JsonPath; //导入依赖的package包/类
public static void assertJsonEquals(String expected, String actual, String... blacklistedFields) {
    LOG.debug("Comparing expected [{}] to actual [{}]", expected, actual);
    DocumentContext expectedDocument = JsonPath.parse(expected);
    DocumentContext actualDocument = JsonPath.parse(actual);

    if (blacklistedFields != null) {
        removeFields(expectedDocument, blacklistedFields);
        removeFields(actualDocument, blacklistedFields);
    }

    try {
        ObjectMapper mapper = new ObjectMapper();

        JsonNode expectedNode = mapper.readTree(expectedDocument.jsonString());
        JsonNode actualNode = mapper.readTree(actualDocument.jsonString());

        assertEquals(expectedNode, actualNode);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
开发者ID:Atypon-OpenSource,项目名称:wayf-cloud,代码行数:22,代码来源:HttpTestUtil.java

示例8: createALotOfInstancesWithDifferentUpdateDate

import com.jayway.jsonpath.JsonPath; //导入依赖的package包/类
@BeforeClass
public void createALotOfInstancesWithDifferentUpdateDate() throws Exception {
    GraphQLResult result = executeSchemaQuery(addSchema);
    assertTrue(result.isSuccessful());

    for (int i = 0; i < INSTANCE_COUNT; i++) {
        result = instanceService.executeQuery(
                addInstance, buildVariableMap(ORDERED_TYPE_NAME), buildSchemaWriteAccess(), DEFAULT_MAX_RECURSE_DEPTH);
        assertTrue(result.isSuccessful());
        /* Sleep 1 millisecond, just to have a slight spread of 'updateDate'. */
        TimeUnit.MILLISECONDS.sleep(1);
    }

    /* Prerequisites for ordering tests: 'updateDate' has unique values and is of type Long. */
    result = instanceService.executeQuery(
            findInstances, buildVariableMap(ORDERED_TYPE_NAME), buildSchemaWriteAccess(), DEFAULT_MAX_RECURSE_DEPTH);
    assertTrue(result.isSuccessful(), result.getErrors().toString());
    String json = objectMapper.writeValueAsString(result.getData());
    Object[] dates = JsonPath.<JSONArray>read(json, "$.viewer.instances.edges[*].node.updateDate").toArray();
    assertTrue(dates[0] instanceof Long, "Expected updateDate-s to be instances of Long");
    assertEquals(new HashSet<>(asList(dates)).size(), INSTANCE_COUNT, "All updateDate-s should have been different.");
}
 
开发者ID:nfl,项目名称:gold,代码行数:23,代码来源:OrderByTest.java

示例9: testNavDate

import com.jayway.jsonpath.JsonPath; //导入依赖的package包/类
@Test
public void testNavDate() throws IOException {
  OffsetDateTime navDate = OffsetDateTime.of(1970, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC);
  Manifest manifest = new Manifest("http://some.uri", "A label for the Manifest");
  manifest.setNavDate(navDate);
  String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(manifest);
  DocumentContext ctx = JsonPath.parse(json);
  JsonPathAssert.assertThat(ctx).jsonPathAsString("navDate").isEqualTo("1970-01-01T00:00:00Z");
  assertThat(mapper.readValue(json, Manifest.class).getNavDate()).isEqualTo(manifest.getNavDate());

  Collection coll = new Collection("http://some.uri", "A label for the Collection");
  coll.setNavDate(navDate);
  json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(coll);
  ctx = JsonPath.parse(json);
  JsonPathAssert.assertThat(ctx).jsonPathAsString("navDate").isEqualTo("1970-01-01T00:00:00Z");
  assertThat(mapper.readValue(json, Collection.class).getNavDate()).isEqualTo(navDate);
}
 
开发者ID:dbmdz,项目名称:iiif-apis,代码行数:18,代码来源:JsonMappingTest.java

示例10: convert

import com.jayway.jsonpath.JsonPath; //导入依赖的package包/类
public AttributeRequest convert(String topic, MqttMessage msg) {
    deviceNameTopicPattern = checkAndCompile(deviceNameTopicPattern, deviceNameTopicExpression);
    attributeKeyTopicPattern = checkAndCompile(attributeKeyTopicPattern, attributeKeyTopicExpression);
    requestIdTopicPattern = checkAndCompile(requestIdTopicPattern, requestIdTopicExpression);

    String data = new String(msg.getPayload(), StandardCharsets.UTF_8);
    DocumentContext document = JsonPath.parse(data);

    AttributeRequest.AttributeRequestBuilder builder = AttributeRequest.builder();
    builder.deviceName(eval(topic, deviceNameTopicPattern, document, deviceNameJsonExpression));
    builder.attributeKey(eval(topic, attributeKeyTopicPattern, document, attributeKeyJsonExpression));
    builder.requestId(Integer.parseInt(eval(topic, requestIdTopicPattern, document, requestIdJsonExpression)));

    builder.clientScope(this.isClientScope());
    builder.topicExpression(this.getResponseTopicExpression());
    builder.valueExpression(this.getValueExpression());
    return builder.build();
}
 
开发者ID:thingsboard,项目名称:thingsboard-gateway,代码行数:19,代码来源:AttributeRequestsMapping.java

示例11: sendSuccessMaskRequestResponse

import com.jayway.jsonpath.JsonPath; //导入依赖的package包/类
@Test
public void sendSuccessMaskRequestResponse() throws Exception {
    when(request.getRequestURI()).thenReturn("/api/attachments");
    when(request.getMethod()).thenReturn("PUT");

    String json = producer.createEventJson(request, response, "test", "admin", "key");
    assertEquals("admin", JsonPath.read(json, "$.login"));
    assertEquals("key", JsonPath.read(json, "$.userKey"));
    assertEquals("test", JsonPath.read(json, "$.tenant"));
    assertEquals("attachments changed", JsonPath.read(json, "$.operationName"));
    assertEquals("/api/attachments", JsonPath.read(json, "$.operationUrl"));
    assertEquals("PUT", JsonPath.read(json, "$.httpMethod"));
    assertEquals("{domain=test}", JsonPath.read(json, "$.requestHeaders").toString());
    assertEquals("{domain=test}", JsonPath.read(json, "$.responseHeaders").toString());
    assertEquals(Integer.valueOf(200), JsonPath.read(json, "$.httpStatusCode"));
    assertEquals("HTTP", JsonPath.read(json, "$.channelType"));
    assertEquals("{\"content\":{\"value\":\"mask\",\"text\":\"mask\"}}", JsonPath.read(json, "$.requestBody"));
    assertEquals("{\"content\":{\"value\":\"mask\",\"text\":\"mask\"}}", JsonPath.read(json, "$.responseBody"));
}
 
开发者ID:xm-online,项目名称:xm-commons,代码行数:20,代码来源:TimelineEventProducerUnitTest.java

示例12: sendSuccessMaskResponse

import com.jayway.jsonpath.JsonPath; //导入依赖的package包/类
@Test
public void sendSuccessMaskResponse() throws Exception {
    when(request.getRequestURI()).thenReturn("/api/attachments/1");
    when(request.getMethod()).thenReturn("GET");

    String json = producer.createEventJson(request, response, "test", "admin", "key");
    assertEquals("admin", JsonPath.read(json, "$.login"));
    assertEquals("key", JsonPath.read(json, "$.userKey"));
    assertEquals("test", JsonPath.read(json, "$.tenant"));
    assertEquals("attachments viewed", JsonPath.read(json, "$.operationName"));
    assertEquals("/api/attachments/1", JsonPath.read(json, "$.operationUrl"));
    assertEquals("GET", JsonPath.read(json, "$.httpMethod"));
    assertEquals("{domain=test}", JsonPath.read(json, "$.requestHeaders").toString());
    assertEquals("{domain=test}", JsonPath.read(json, "$.responseHeaders").toString());
    assertEquals(Integer.valueOf(200), JsonPath.read(json, "$.httpStatusCode"));
    assertEquals("HTTP", JsonPath.read(json, "$.channelType"));
    assertEquals(CONTENT, JsonPath.read(json, "$.requestBody"));
    assertEquals("{\"content\":{\"value\":\"mask\",\"text\":\"someText\"}}", JsonPath.read(json, "$.responseBody"));
}
 
开发者ID:xm-online,项目名称:xm-commons,代码行数:20,代码来源:TimelineEventProducerUnitTest.java

示例13: getTransformationProperties

import com.jayway.jsonpath.JsonPath; //导入依赖的package包/类
@Test
public void getTransformationProperties() throws Exception {
    preInitNonCreationTests();
    MvcResult result = mvc.perform(
        get(GET_PROPERTIES_VALID_URL)
    ).andDo(print())
        .andExpect(status().is(200))
        .andExpect(content().contentType(DEFAULT_CHARSET_HAL_JSON))
        .andExpect(jsonPath("$.properties").isArray())
        .andExpect(jsonPath("$.properties").isNotEmpty())
        .andExpect(jsonPath("$.properties[0].key").isString())
        .andExpect(jsonPath("$.properties[0].type").isString())
        .andExpect(jsonPath("$.properties[0].description").isString())
        .andExpect(jsonPath("$.properties[0].required").isBoolean())
        .andExpect(jsonPath("$.links[0].rel").value("self"))
        .andExpect(jsonPath("$.links[0].href")
            .value("http://localhost/api/csars/kubernetes-cluster/transformations/p-a/properties"))
        .andReturn();

    MockHttpServletResponse response = result.getResponse();
    String responseJson = new String(response.getContentAsByteArray());
    String[] values = JsonPath.parse(responseJson).read("$.properties[*].value", String[].class);
    long nullCount = Arrays.asList(values).stream().filter(Objects::isNull).count();
    long testCount = Arrays.asList(values).stream().filter(e -> e != null && e.equals(PROPERTY_TEST_DEFAULT_VALUE)).count();
    assertEquals(7, nullCount);
    assertEquals(1, testCount);
}
 
开发者ID:StuPro-TOSCAna,项目名称:TOSCAna,代码行数:28,代码来源:TransformationControllerTest.java

示例14: testElasticsearchRunning

import com.jayway.jsonpath.JsonPath; //导入依赖的package包/类
public void testElasticsearchRunning() throws IOException {
	MarcElasticsearchClient client = new MarcElasticsearchClient();
	HttpEntity response = client.rootRequest();
	assertNull(response.getContentEncoding());
	assertEquals("content-type", response.getContentType().getName());
	assertEquals("application/json; charset=UTF-8", response.getContentType().getValue());
	String content = EntityUtils.toString(response);
	Object jsonObject = jsonProvider.parse(content);
	// JsonPath.fileToDict(jsonObject, jsonPath);
	
	// JsonPathCache<? extends XmlFieldInstance> cache = new JsonPathCache(content);
	assertEquals("elasticsearch", JsonPath.read(jsonObject, "$.cluster_name"));
	assertEquals("hTkN47N", JsonPath.read(jsonObject, "$.name"));
	assertEquals("1gxeFwIRR5-tkEXwa2wVIw", JsonPath.read(jsonObject, "$.cluster_uuid"));
	assertEquals("You Know, for Search", JsonPath.read(jsonObject, "$.tagline"));
	assertEquals("5.5.1", JsonPath.read(jsonObject, "$.version.number"));
	assertEquals("6.6.0", JsonPath.read(jsonObject, "$.version.lucene_version"));
	assertEquals(2, client.getNumberOfTweets());
}
 
开发者ID:pkiraly,项目名称:metadata-qa-marc,代码行数:20,代码来源:MarcElasticsearchClientTest.java

示例15: getAllPullRequests_should_return_all_pull_requests_as_list

import com.jayway.jsonpath.JsonPath; //导入依赖的package包/类
@Test
public void getAllPullRequests_should_return_all_pull_requests_as_list() throws Exception {
	final Repository repo = mock( Repository.class );
	final String json = new String( Files.readAllBytes(
			Paths.get( "src/test/resources/org/retest/rebazer/service/bitbucketservicetest/response.json" ) ) );
	final DocumentContext documentContext = JsonPath.parse( json );
	when( config.getTeam() ).thenReturn( "test_team" );
	when( repo.getName() ).thenReturn( "test_repo_name" );
	when( bitbucketTemplate.getForObject( anyString(), eq( String.class ) ) ).thenReturn( json );

	final int expectedId = (int) documentContext.read( "$.values[0].id" );
	final String expectedUrl =
			"/repositories/" + config.getTeam() + "/" + repo.getName() + "/pullrequests/" + expectedId;
	final List<PullRequest> expected = Arrays.asList( PullRequest.builder().id( expectedId ).repo( repo.getName() )
			.source( documentContext.read( "$.values[0].source.branch.name" ) )
			.destination( documentContext.read( "$.values[0].destination.branch.name" ) ).url( expectedUrl )
			.lastUpdate( documentContext.read( "$.values[0].updated_on" ) ).build() );
	final List<PullRequest> actual = cut.getAllPullRequests( repo );

	assertThat( actual ).isEqualTo( expected );
}
 
开发者ID:retest,项目名称:rebazer,代码行数:22,代码来源:BitbucketServiceTest.java


注:本文中的com.jayway.jsonpath.JsonPath类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。