zoukankan      html  css  js  c++  java
  • JsonPath的使用

     

     

    语法:

    JsonPath

    描述

    $

    根节点

    @

    当前节点

    .or[]

    子节点

    ..

    选择所有符合条件的节点

    *

    所有节点

    []

    迭代器标示,如数组下标

    [,]

    支持迭代器中做多选

    [start:end:step]

    数组切片运算符

    ?()

    支持过滤操作

    ()

    支持表达式计算

    需要的jar包:

    commons-lang-2.6.jar
    json-path-0.8.1.jar
    json-smart-1.1.1.jar

    对于如下的json,通过实例介绍JsonPath的使用

    复制代码
    { "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,
            "isbn": "0-553-21311-3"
          }
        ],
        "bicycle": {
          "color": "red",
          "price": 19.95
        }
      }
    }
    复制代码

    代码:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    private static void jsonPathTest() {
        JSONObject json = jsonTest();//调用自定义的jsonTest()方法获得json对象,生成上面的json
         
        //输出book[0]的author值
        String author = JsonPath.read(json, "$.store.book[0].author");
         
        //输出全部author的值,使用Iterator迭代
        List<String> authors = JsonPath.read(json, "$.store.book[*].author");
         
        //输出book[*]中category == 'reference'的book
        List<Object> books = JsonPath.read(json, "$.store.book[?(@.category == 'reference')]");              
         
        //输出book[*]中price>10的book
        List<Object> books = JsonPath.read(json, "$.store.book[?(@.price>10)]");
         
        //输出book[*]中含有isbn元素的book
        List<Object> books = JsonPath.read(json, "$.store.book[?(@.isbn)]");
         
        //输出该json中所有price的值
        List<Double> prices = JsonPath.read(json, "$..price");
         
        //可以提前编辑一个路径,并多次使用它
        JsonPath path = JsonPath.compile("$.store.book[*]");
        List<Object> books = path.read(json);
    }
     
     
  • 相关阅读:
    js将url转换二维码
    百度地图api使用
    js字符串转日期兼容性
    Object.keys的使用
    Web App和Native App的比较
    数组转为对象
    常用meta整理
    git merge和git rebase的区别
    GitHub 翻译之 'Hello-world' 翻译
    js数据类型
  • 原文地址:https://www.cnblogs.com/wq920/p/10594771.html
Copyright © 2011-2022 走看看