【问题标题】:Get custom object by id from json java jsonpath从 json java jsonpath 通过 id 获取自定义对象
【发布时间】:2021-06-26 19:10:50
【问题描述】:

我正在尝试通过 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

【问题讨论】:

标签: java jsonpath jayway


【解决方案1】:

这里有两件事

  1. 过滤时必须使用占位符? 而不是*,否则过滤器将被忽略。
  2. read() 将返回一个列表,而不是单个对象。

所以,我想,你需要这样的东西

String json = "{\r\n"
        + "  \"user\": [\r\n"
        + "    {\r\n"
        + "      \"id\": \"1\",\r\n"
        + "      \"login\": \"client1\",\r\n"
        + "      \"password\": \"qwerty\",\r\n"
        + "      \"email\": \"client@gmail.com\"\r\n"
        + "    }\r\n"
        + "  ]\r\n"
        + "}";

Predicate filterById = filter(where("id").is("1"));
List<User> users = JsonPath.parse(json).read("$.user[?]",filterById );

System.out.println(users);

参考:Filter Predicates

where("category").is("fiction").and("price").lte(10D) );

List<Map<String, Object>> books =     
parse(json).read("$.store.book[?]", cheapFictionFilter); 

注意路径中过滤器的占位符?。当提供多个过滤器时,它们的应用顺序是占位符的数量必须与提供的过滤器的数量相匹配。您可以在一个过滤操作[?, ?] 中指定多个谓词占位符,两个谓词必须匹配。

【讨论】:

  • $.user[?] 不是有效的 JSON 路径语法。 Jayway真的支持吗?它有什么作用?
  • 找到它:github.com/json-path/JsonPath 请参阅“过滤谓词”。看起来这是该库采用的一种机制,其功能类似于字符串插值,但用于注入其他地方定义的过滤器。
  • 是的,占位符 ? 的作用类似于 SQL 查询中的绑定参数。
猜你喜欢
  • 1970-01-01
  • 2023-02-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-08
  • 1970-01-01
  • 2014-06-29
  • 1970-01-01
相关资源
最近更新 更多