io.restassured.path.json.JsonPath类的使用及代码示例

x33g5p2x  于2022-01-22 转载在 其他  
字(17.6k)|赞(0)|评价(0)|浏览(135)

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

JsonPath介绍

[英]JsonPath is an alternative to using XPath for easily getting values from a Object document. It follows the Groovy GPath syntax when getting an object from the document. You can regard it as an alternative to XPath for JSON. E.g. given the following Object document:

{ "store": { 
"book": [ 
{ "category": "reference", 
"author": "Nigel Rees", 
"title": "Sayings of the Century", 
"price": 8.95 
}, 
{ "category": "fiction", 
"author": "Evelyn Waugh", 
"title": "Sword of Honour", 
"price": 12.99 
}, 
{ "category": "fiction", 
"author": "Herman Melville", 
"title": "Moby Dick", 
"isbn": "0-553-21311-3", 
"price": 8.99 
}, 
{ "category": "fiction", 
"author": "J. R. R. Tolkien", 
"title": "The Lord of the Rings", 
"isbn": "0-395-19395-8", 
"price": 22.99 
} 
], 
"bicycle": { 
"color": "red", 
"price": 19.95 
} 
} 
}

To get a list of all book categories:

List<String> categories = with(Object).get("store.book.category");

Get the first book category:

String category = with(Object).get("store.book[0].category");

Get the last book category:

String category = with(Object).get("store.book[-1].category");

Get all books with price between 5 and 15:

List<Map> books = with(Object).get("store.book.findAll { book -> book.price >= 5 && book.price  
  
The JsonPath implementation of rest-assured uses a Groovy shell to evaluate expressions so be careful when injecting 
user input into the expression. For example avoid doing this: 
  
String name = System.console().readLine(); 
List<Map> books = with(Object).get("store.book.findAll { book -> book.author == " + name + " }"); 
 
Instead use the  
#param(java.lang.String,java.lang.Object) method like this: 
  
String name = System.console().readLine(); 
List<Map> books = with(Object).param("name", name).get("store.book.findAll { book -> book.author == name }");

[中]JsonPath是使用XPath从对象文档轻松获取值的替代方法。从文档中获取对象时,它遵循GroovyGPath语法。您可以将其视为用于JSON的XPath的替代方案。例如,给定以下对象文档:

{ "store": { 
"book": [ 
{ "category": "reference", 
"author": "Nigel Rees", 
"title": "Sayings of the Century", 
"price": 8.95 
}, 
{ "category": "fiction", 
"author": "Evelyn Waugh", 
"title": "Sword of Honour", 
"price": 12.99 
}, 
{ "category": "fiction", 
"author": "Herman Melville", 
"title": "Moby Dick", 
"isbn": "0-553-21311-3", 
"price": 8.99 
}, 
{ "category": "fiction", 
"author": "J. R. R. Tolkien", 
"title": "The Lord of the Rings", 
"isbn": "0-395-19395-8", 
"price": 22.99 
} 
], 
"bicycle": { 
"color": "red", 
"price": 19.95 
} 
} 
}

要获取所有图书类别的列表:

List<String> categories = with(Object).get("store.book.category");

获取第一个图书类别:

String category = with(Object).get("store.book[0].category");

获取最后一个图书类别:

String category = with(Object).get("store.book[-1].category");

购买价格在5到15之间的所有书籍:

List<Map> books = with(Object).get("store.book.findAll { book -> book.price >= 5 && book.price  
  
The JsonPath implementation of rest-assured uses a Groovy shell to evaluate expressions so be careful when injecting 
user input into the expression. For example avoid doing this: 
  
String name = System.console().readLine(); 
List<Map> books = with(Object).get("store.book.findAll { book -> book.author == " + name + " }"); 
 
Instead use the  
#param(java.lang.String,java.lang.Object) method like this: 
  
String name = System.console().readLine(); 
List<Map> books = with(Object).param("name", name).get("store.book.findAll { book -> book.author == name }");

代码示例

代码示例来源:origin: rest-assured/rest-assured

/**
 * Get the result of an Object path expression as a list.
 *
 * @param path The Object path.
 * @param <T>  The list type
 * @return The object matching the Object path. A {@link java.lang.ClassCastException} will be thrown if the object
 * cannot be casted to the expected type.
 */
public <T> List<T> getList(String path) {
  return get(path);
}

代码示例来源:origin: rest-assured/rest-assured

/**
 * Instantiate a new JsonPath instance.
 *
 * @param reader The reader containing the Object document
 */
public static JsonPath from(Reader reader) {
  return new JsonPath(reader);
}

代码示例来源:origin: rest-assured/rest-assured

Object object = getJsonObject(path);
if (object == null) {
  return null;
} else if (object instanceof List || object instanceof Map) {
  object = objectToString(object);
} else {
  return ObjectConverter.convertObjectTo(object, objectType);
return jsonStringToObject((String) object, objectType);

代码示例来源:origin: rest-assured/rest-assured

/**
 * Configure JsonPath to use a specific Jackson object mapper factory
 *
 * @param factory The Jackson object mapper factory instance
 * @return a new JsonPath instance
 */
public JsonPath using(Jackson1ObjectMapperFactory factory) {
  return new JsonPath(this, getJsonPathConfig().jackson1ObjectMapperFactory(factory));
}

代码示例来源:origin: camunda/camunda-bpm-platform

protected void verifyHistoricJobLogEntries(String content) {
 String returnedId = from(content).getString("[0].id");
 String returnedTimestamp = from(content).getString("[0].timestamp");
 String returnedRemovalTime = from(content).getString("[0].removalTime");
 String returnedJobId = from(content).getString("[0].jobId");
 String returnedJobDueDate = from(content).getString("[0].jobDueDate");
 int returnedJobRetries = from(content).getInt("[0].jobRetries");
 long returnedJobPriority = from(content).getLong("[0].jobPriority");
 String returnedJobExceptionMessage = from(content).getString("[0].jobExceptionMessage");
 String returnedJobDefinitionId = from(content).getString("[0].jobDefinitionId");
 String returnedJobDefinitionType = from(content).getString("[0].jobDefinitionType");
 String returnedJobDefinitionConfiguration = from(content).getString("[0].jobDefinitionConfiguration");
 String returnedActivityId = from(content).getString("[0].activityId");
 String returnedExecutionId = from(content).getString("[0].executionId");
 String returnedProcessInstanceId = from(content).getString("[0].processInstanceId");
 String returnedProcessDefinitionId = from(content).getString("[0].processDefinitionId");
 String returnedProcessDefinitionKey = from(content).getString("[0].processDefinitionKey");
 String returnedDeploymentId = from(content).getString("[0].deploymentId");
 String returnedRootProcessInstanceId = from(content).getString("[0].rootProcessInstanceId");
 boolean returnedCreationLog = from(content).getBoolean("[0].creationLog");
 boolean returnedFailureLog = from(content).getBoolean("[0].failureLog");
 boolean returnedSuccessLog = from(content).getBoolean("[0].successLog");
 boolean returnedDeletionLog = from(content).getBoolean("[0].deletionLog");

代码示例来源:origin: camunda/camunda-bpm-platform

protected void verifyExampleUserResponse(Response response) {
 String content = response.asString();
 List<String> instances = from(content).getList("");
 Assert.assertEquals("There should be one user returned.", 1, instances.size());
 Assert.assertNotNull("The returned user should not be null.", instances.get(0));
 String returendLastName = from(content).getString("[0].lastName");
 String returnedFirstName = from(content).getString("[0].firstName");
 String returnedEmail = from(content).getString("[0].email");
 Assert.assertEquals(MockProvider.EXAMPLE_USER_FIRST_NAME, returnedFirstName);
 Assert.assertEquals(MockProvider.EXAMPLE_USER_LAST_NAME, returendLastName);
 Assert.assertEquals(MockProvider.EXAMPLE_USER_EMAIL, returnedEmail);
}

代码示例来源:origin: camunda/camunda-bpm-platform

protected void checkProcessInstanceResult(String content, int idx) {
 //resultType should be set to process definition
 String resultType = from(content).get("[" + idx + "].resultType");
 Assert.assertEquals(MessageCorrelationResultType.ProcessDefinition.name(), resultType);
 //process instance should be filled and execution should be null
 Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID, from(content).get("[" + idx + "].processInstance.id"));
 Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID, from(content).get("[" + idx + "].processInstance.definitionId"));
 Assert.assertNull(from(content).get("[" + idx + "].execution"));
}

代码示例来源:origin: camunda/camunda-bpm-platform

private void verifyCmmnDeploymentValues(Deployment mockDeployment, String responseContent) {
 JsonPath path = from(responseContent);
 verifyStandardDeploymentValues(mockDeployment, path);
 Map<String, HashMap<String, Object>> deployedCaseDefinitions = path.getMap(PROPERTY_DEPLOYED_CASE_DEFINITIONS);
 assertEquals(1, deployedCaseDefinitions.size());
 HashMap caseDefinitionDto = deployedCaseDefinitions.get(EXAMPLE_CASE_DEFINITION_ID);
 assertNotNull(caseDefinitionDto);
 verifyCmnDeployment(caseDefinitionDto);
 assertNull(path.get(PROPERTY_DEPLOYED_PROCESS_DEFINITIONS));
 assertNull(path.get(PROPERTY_DEPLOYED_DECISION_DEFINITIONS));
 assertNull(path.get(PROPERTY_DEPLOYED_DECISION_REQUIREMENTS_DEFINITIONS));
}

代码示例来源:origin: camunda/camunda-bpm-platform

private void verifyDeploymentLink(Deployment mockDeployment, String responseContent) {
 List<Map<String, String>> returnedLinks = from(responseContent).getList("links");
 assertEquals(1, returnedLinks.size());
 Map<String, String> returnedLink = returnedLinks.get(0);
 assertEquals(HttpMethod.GET, returnedLink.get("method"));
 assertTrue(returnedLink.get("href").endsWith(RESOURCE_URL + "/" + mockDeployment.getId()));
 assertEquals("self", returnedLink.get("rel"));
}

代码示例来源:origin: camunda/camunda-bpm-platform

List<Map<String, String>> jobDefinitions = from(content).getList("");
String returnedId = from(content).getString("[0].id");
String returnedProcessDefinitionId = from(content).getString("[0].processDefinitionId");
String returnedProcessDefinitionKey = from(content).getString("[0].processDefinitionKey");
String returnedActivityId = from(content).getString("[0].activityId");
String returnedJobType = from(content).getString("[0].jobType");
String returnedJobConfiguration = from(content).getString("[0].jobConfiguration");
boolean returnedSuspensionState = from(content).getBoolean("[0].suspended");
Long returnedJobPriority = from(content).getObject("[0].overridingJobPriority", Long.class);

代码示例来源:origin: camunda/camunda-bpm-platform

protected void verifyBatchListJson(String batchListJson) {
 List<Object> batches = from(batchListJson).get();
 assertEquals("There should be one batch returned.", 1, batches.size());
 BatchDto batch = from(batchListJson).getObject("[0]", BatchDto.class);
 assertNotNull("The returned batch should not be null.", batch);
 assertEquals(MockProvider.EXAMPLE_BATCH_ID, batch.getId());
 assertEquals(MockProvider.EXAMPLE_BATCH_TYPE, batch.getType());
 assertEquals(MockProvider.EXAMPLE_BATCH_TOTAL_JOBS, batch.getTotalJobs());
 assertEquals(MockProvider.EXAMPLE_BATCH_JOBS_CREATED, batch.getJobsCreated());
 assertEquals(MockProvider.EXAMPLE_BATCH_JOBS_PER_SEED, batch.getBatchJobsPerSeed());
 assertEquals(MockProvider.EXAMPLE_INVOCATIONS_PER_BATCH_JOB, batch.getInvocationsPerBatchJob());
 assertEquals(MockProvider.EXAMPLE_SEED_JOB_DEFINITION_ID, batch.getSeedJobDefinitionId());
 assertEquals(MockProvider.EXAMPLE_MONITOR_JOB_DEFINITION_ID, batch.getMonitorJobDefinitionId());
 assertEquals(MockProvider.EXAMPLE_BATCH_JOB_DEFINITION_ID, batch.getBatchJobDefinitionId());
 assertEquals(MockProvider.EXAMPLE_TENANT_ID, batch.getTenantId());
 assertEquals(MockProvider.EXAMPLE_USER_ID, batch.getCreateUserId());
 assertTrue(batch.isSuspended());
}

代码示例来源:origin: camunda/camunda-bpm-platform

List<Map<String, String>> filters = from(content).getList("");
String returnedFilterId = from(content).getString("[0].id");
String returnedResourceType = from(content).getString("[0].resourceType");
String returnedName = from(content).getString("[0].name");
String returnedOwner = from(content).getString("[0].owner");
Map<String, Object> returnedQuery = from(content).getJsonObject("[0].query");
Map<String, Object> returnedProperties = from(content).getJsonObject("[0].properties");
returnedFilterId = from(content).getString("[1].id");
returnedResourceType = from(content).getString("[1].resourceType");
returnedName = from(content).getString("[1].name");
returnedOwner = from(content).getString("[1].owner");
returnedQuery = from(content).getJsonObject("[1].query");
returnedProperties = from(content).getJsonObject("[1].properties");

代码示例来源:origin: camunda/camunda-bpm-platform

@Test
public void testGetFilterWithSingleSorting() {
 TaskQuery query = new TaskQueryImpl()
  .orderByTaskName().desc();
 Filter filter = new FilterEntity("Task").setName("test").setQuery(query);
 when(filterServiceMock.getFilter(EXAMPLE_FILTER_ID)).thenReturn(filter);
 Response response = given()
  .pathParam("id", EXAMPLE_FILTER_ID)
 .then().expect()
  .statusCode(Status.OK.getStatusCode())
 .when()
  .get(SINGLE_FILTER_URL);
 // validate sorting content
 String content = response.asString();
 List<Map<String, Object>> sortings = from(content).getJsonObject("query.sorting");
 assertThat(sortings).hasSize(1);
 assertSorting(sortings.get(0), SORT_BY_NAME_VALUE, SORT_ORDER_DESC_VALUE);
}

代码示例来源:origin: camunda/camunda-bpm-platform

@Test
public void testIncompleteExecution() {
 setUpMockExecutionQuery(createIncompleteMockExecutions());
 Response response = expect().statusCode(Status.OK.getStatusCode())
   .when().get(EXECUTION_QUERY_URL);
 String content = response.asString();
 String returnedProcessInstanceId = from(content).getString("[0].processInstanceId");
 Assert.assertNull("Should be null, as it is also null in the original execution on the server.",
   returnedProcessInstanceId);
}

代码示例来源:origin: camunda/camunda-bpm-platform

UserOperationLogEntryDto actual = from(json).getObject("[0]", UserOperationLogEntryDto.class);
assertEquals(MockProvider.EXAMPLE_USER_OPERATION_LOG_ID, actual.getId());
assertEquals(MockProvider.EXAMPLE_DEPLOYMENT_ID, actual.getDeploymentId());
assertEquals(MockProvider.EXAMPLE_BATCH_ID, actual.getBatchId());
assertEquals(MockProvider.EXAMPLE_USER_ID, actual.getUserId());
assertEquals(MockProvider.EXAMPLE_USER_OPERATION_TIMESTAMP, from(json).getString("[0].timestamp"));
assertEquals(MockProvider.EXAMPLE_USER_OPERATION_ID, actual.getOperationId());
assertEquals(MockProvider.EXAMPLE_USER_OPERATION_TYPE, actual.getOperationType());

代码示例来源:origin: rest-assured/rest-assured

return getObject(path, typeRef.getTypeAsClass());

代码示例来源:origin: camunda/camunda-bpm-platform

public static JsonPath from(String json) {
 return JsonPath.from(json).using(new DefaultJackson2ObjectMapperFactory() {
  public ObjectMapper create(Class cls, String charset) {
   return JacksonConfigurator.configureObjectMapper(super.create(cls, charset));
  }
 });
}

代码示例来源:origin: camunda/camunda-bpm-platform

List<String> reportResults = from(content).getList("");
Assert.assertEquals("There should be two report results returned.", 2, reportResults.size());
Assert.assertNotNull(reportResults.get(0));
String returnedDefinitionId = from(content).getString("[0].decisionDefinitionId");
String returnedDefinitionKey = from(content).getString("[0].decisionDefinitionKey");
String returnedDefinitionName = from(content).getString("[0].decisionDefinitionName");
int returnedDefinitionVersion = from(content).getInt("[0].decisionDefinitionVersion");
int returnedTTL = from(content).getInt("[0].historyTimeToLive");
long returnedFinishedCount= from(content).getLong("[0].finishedDecisionInstanceCount");
long returnedCleanableCount = from(content).getLong("[0].cleanableDecisionInstanceCount");
String returnedTenantId = from(content).getString("[0].tenantId");

代码示例来源:origin: camunda/camunda-bpm-platform

private void verifyTenantIdListParameterResponse(Response response) {
 String content = response.asString();
 List<String> historicDetails = from(content).getList("");
 assertThat(historicDetails).hasSize(4);
 String returnedTenantId1 = from(content).getString("[0].tenantId");
 String returnedTenantId2 = from(content).getString("[1].tenantId");
 String returnedTenantId3 = from(content).getString("[2].tenantId");
 String returnedTenantId4 = from(content).getString("[3].tenantId");
 assertThat(returnedTenantId1).isEqualTo(MockProvider.EXAMPLE_TENANT_ID);
 assertThat(returnedTenantId2).isEqualTo(MockProvider.EXAMPLE_TENANT_ID);
 assertThat(returnedTenantId3).isEqualTo(MockProvider.ANOTHER_EXAMPLE_TENANT_ID);
 assertThat(returnedTenantId4).isEqualTo(MockProvider.ANOTHER_EXAMPLE_TENANT_ID);
}

代码示例来源:origin: camunda/camunda-bpm-platform

protected void checkResult(String content) {
 Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID, from(content).get("[" + 0 + "].id"));
 Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID, from(content).get("[" + 0+ "].definitionId"));
 Assert.assertEquals(MockProvider.ANOTHER_EXAMPLE_PROCESS_INSTANCE_ID, from(content).get("[" + 1 + "].id"));
 Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID, from(content).get("[" + 1+ "].definitionId"));
}

相关文章