【问题标题】:Java JsonPath - Get all paths of attributes that are primitive typesJava JsonPath - 获取原始类型属性的所有路径
【发布时间】:2021-12-30 04:41:01
【问题描述】:

我想从属性类型为原始(不是对象或数组)的 json 文件中查找所有 Json 路径

考虑 jsonString

{
   "header": {
       "version": 2,
       "original": "ori",
       "parent": "par",
       "eventId": 11,
       "correlation": "uuid",
       "timestamp": "03.04.2020",
       "local": true,
       "location": {
           "facility": {
               "id": 3,
               "type": "en"
           }
       }
   },
   "body": {
       "field": 3
   }
} 

我使用以下代码:

Configuration configuration = Configuration.builder().options(Option.AS_PATH_LIST).build();
List<String> paths = JsonPath.using(configuration).parse(jsonString).read("$..*");

实际结果: 模式 "$..*" 向我返回 json 中存在的所有路径:

  • $['header']
  • $['body']
  • $['header']['version']
  • $['header']['original']
  • $['header']['parent']
  • $['header']['eventId']
  • $['header']['correlation']
  • $['header']['timestamp']
  • $['header']['local']
  • $['header']['location']
  • $['header']['location']['facility']
  • $['header']['location']['facility']['id']
  • $['header']['location']['facility']['type']
  • $['body']['field']

预期结果:我只需要得到这些:

  • $['header']['version']
  • $['header']['original']
  • $['header']['parent']
  • $['header']['eventId']
  • $['header']['correlation']
  • $['header']['timestamp']
  • $['header']['local']
  • $['header']['location']['facility']['id']
  • $['header']['location']['facility']['type']
  • $['body']['field']

过滤器应该是通用的,因此它可以解析作为输入给出的任何 json 格式。

【问题讨论】:

    标签: java json jsonpath jsonparser


    【解决方案1】:

    您可以使用下面的 JSONPath,它将给出包含对象或数组的路径,然后您可以将其从 JSONPath 的整个列表中排除。

    JSONPath

    $..*[?(@.length != 0)]
    

    Java 代码

    List<String> allPaths = JsonPath.using(configuration).parse(jsonString).read("$..*");
    List<String> exludedPaths = JsonPath.using(configuration).parse(jsonString).read("$..*[?(@.length != 0)]");
    List<String> primitivePaths = allPaths.removeAll(exludedPaths);
    

    【讨论】:

      猜你喜欢
      • 2012-03-11
      • 2021-09-02
      • 2010-11-13
      • 2011-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-04
      相关资源
      最近更新 更多