java - 如何将 Rest-Assure 反序列化到 TodoList?
问题描述
我想将 Rest-Assure 响应中的 Json 数组反序列化到 TodoList 中,并将 Todo 对象作为列表中的元素。我有课 Todo
import java.util.Date;
public class Todo {
private Long id;
private String name;
private String description;
private Date targetDate;
private Boolean isDone;
protected Todo() {
}
/**
* Get the id of the bank.
* @return id for the bank
*/
public Long getId() {
return id;
}
public Todo(String name, String description, Date targetDate, boolean isDone) {
this.name = name;
this.description = description;
this.targetDate = targetDate;
this.isDone = isDone;
}
public void setName( String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public String getDescription() {
return this.description;
}
public Date getTargetDate() {
return this.targetDate;
}
public Boolean getIsDone() {
return this.isDone;
}
public void setId(Long id) {
this.id = id;
}
public void setDescription(String description) {
this.description = description;
}
public void setTargetDate(Date targetDate) {
this.targetDate = targetDate;
}
public void setIsDone(Boolean isDone) {
this.isDone = isDone;
}
}
此类的对象在 ListTodo 类中进行管理
package com.steinko.todo;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
public class TodoList {
private List<Todo> todos = new ArrayList<>();
public void addTodo(Todo todo) {
this.todos.add(todo);
}
public void addAllTodos(Collection<Todo> todos) {
this.todos.addAll(todos);
}
public List<Todo> booksByAuthor(String author) {
return todos.stream()
.filter(book -> Objects.equals(author, book.getName()))
.collect(Collectors.toList());
}
}
我希望 Rest Assure 查询应该提供一个 TodoList。我想从 Json 数组转换为 TodoList 我该怎么做
TodoList result = given().
when().
get("/user/stein/todos").??????
解决方案
请求后get
您可以提取Response
. 然后,您可以抓取JsonPath
并在您的帮助下ObjectMapper
将任何 JSON 转换为 POJO
根据您的代码:
TodoList result = given().
when().
get("/user/stein/todos")
then().
extract().
response(). //here's the Response object of Rest Assured
jsonPath(). //calling json path on response
getObject("$", TodoList.class);
线
getObject("$", TodoList.class);
告诉 JSON Path 将 JSON 转换为以 JSONTodoList.class
的根开头的对象。如果你有这样的回应:
{
"someKey": {
"someOtherKey": {
//here's todo list
}
}
}
那么你可以使用someKey.someOtherKey
而不是$
. 这就像告诉 Object Mapper 从哪里开始 JSON 转换
推荐阅读
- javascript - 在行和列中动态添加值总和
- asp.net - ASP.NET:从一个 SQL 命令填充多个标签
- javascript - 我想做一个本地定时器
- python - 无法从 pygal.maps.world.COUNTRIES 中提取国家代码
- sql-server - SQL Server 2017 哪个版本有代理?
- phpmyadmin - 我更新到 MariaDB 10.2.20 以使用 CTE。仍然在 phpMyAdmin 中得到“无法识别的语句类型。(靠近 WITH)
- scala - Tomcat 7 随机崩溃并出现 ClassNotFoundException
- java - 带有 JDK Compliance 9 和 10 的 Eclipse 中的“Long 类型不可见”
- python - Numba:如何以编程方式打开/关闭即时编译(设置 NUMBA_DISABLE_JIT 环境变量)?
- python - 如何组合元组列表中的唯一值?