本文整理汇总了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;
}
示例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");
}
示例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);
}
}
}
}
示例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;
}
示例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;
}
示例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())));
}
}
示例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);
}
}
示例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.");
}
示例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);
}
示例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();
}
示例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"));
}
示例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"));
}
示例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);
}
示例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());
}
示例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 );
}