我正在尝试通过 Jayway JsonPath 从 json 获取用户对象。我的课是:
public class User{
private String id;
private String name;
private String password;
private String email;
/*getters setters constructor*/
}
和 json 示例:
{
"user": [
{
"id": "1",
"login": "client1",
"password": "qwerty",
"email": "client@gmail.com"
}
]
}
我想得到这样的东西:
public Optional<User> find(String id) throws NoSuchEntityException {
Optional<User> user = Optional.empty();
try{
Path path = Path.of(fileDestination+fileName);
ReadContext ctx = JsonPath.parse(Files.readString(path));
User readUser = ctx.read("$..user[*]",User.class,Filter.filter(where("id").is(id)));
user = Optional.ofNullable(readUser);
} catch (IOException e) {
e.printStackTrace();
}
return user;
}
或者获得如何编码的好建议:D