zoukankan      html  css  js  c++  java
  • JSONPath使用

    JSONPath是fastjson在1.2.0之后支持的。JSONPath是一个很强大的功能。关于JSONPath的介绍请查看官方文档 JSONPath

     官方文档上给出了详细的说明以及使用。但是官方文档没有具体的说明对于JSONPath在JSON数据中的使用,下面我来讲解一下JSONPath在JSON中的使用。

    关于JSONPath在JSON中的使用,在1.2.3的时候,官方 support.odps 下面是有封装的;但是我下载的是1.2.7版本的,在1.2.7版本中在support包下面没有odps包,所以我下面的讲解是基于1.2.7版本的。

    其实要在JSON数据中使用JSONPath很简单,只需要简单的一行代码:

     

    String jsonStr = "{ "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}}}";  
    //Object jsonObject = JSON.parse(jsonStr); // 先解析JSON数据  
    JSONObject jsonObject = JSON.parseObject(jsonStr);  

    如果是json格式的字符串,则先解析为JSONObject,然后就能直接使用JSONPath了。

    System.out.println("
     Book数目:" + JSONPath.eval(jsonObject, "$.store.book.size()"));  
    System.out.println("第一本书title:" + JSONPath.eval(jsonObject, "$.store.book[0].title"));  
    System.out.println("price大于10元的book:" + JSONPath.eval(jsonObject, "$.store.book[price > 10]"));  
    System.out.println("price大于10元的title:" + JSONPath.eval(jsonObject, "$.store.book[price > 10][0].title"));  
    System.out.println("category(类别)为fiction(小说)的book:" + JSONPath.eval(jsonObject, "$.store.book[category = 'fiction']"));  
    System.out.println("bicycle的所有属性值" + JSONPath.eval(jsonObject, "$.store.bicycle.*"));  
    System.out.println("bicycle的color和price属性值" + JSONPath.eval(jsonObject, "$.store.bicycle['color','price']"));  

    输出结果:

     Book数目:2  
    第一本书title:Sayings of the Century  
    price大于10元的book:[{"author":"Evelyn Waugh","title":"Sword of Honour","category":"fiction","price":12.99,"isbn":"0-553-21311-3"}]  
    price大于10元的title:Sword of Honour  
    category(类别)为fiction(小说)的book:[{"author":"Evelyn Waugh","title":"Sword of Honour","category":"fiction","price":12.99,"isbn":"0-553-21311-3"}]  
    bicycle的所有属性值[19.95, red]  
    bicycle的color和price属性值[red, 19.95]  
    nhz94259@163.com
  • 相关阅读:
    leetcode-String to Integer (atoi)
    2014薪水
    Ubunt下的软件集
    ubuntu常用软件
    python模块安装
    ubuntu下玩三国杀
    递归函数
    匿名函数
    装饰器函数
    生成器
  • 原文地址:https://www.cnblogs.com/nhz-M/p/7664708.html
Copyright © 2011-2022 走看看