JSONPath小试

最近在某论坛看到一个关于JSONPath的例子,讲这个东西乃对JSON处理的神器,今日碰到周五,就来试试几把。

一、JSON字符串

{ "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
    }
  }
}

二、基本脚本

public class JSONPathTest {

    public static void main(String[] args) throws Exception {
        InputStream is = JSONPathTest.class.getResourceAsStream("data.json");
        JSONObject jsonObject = JsonPath.read(is, "$");
        //使用JSONPath读取指定值
        Map<String, Object> jsonObj = (Map<String, Object>)JsonPath.read(jsonObject, "$.store.book[0]");
        //读取内容
        System.out.println("category: " + jsonObj.get("category"));
        System.out.println("author: " + jsonObj.get("author"));
        System.out.println("title: " + jsonObj.get("title"));
        System.out.println("price: " + jsonObj.get("price"));

        System.out.println("========================");
        List<String> authors = (List<String>)JsonPath.read(jsonObject, "$.store.book[*].author");
        for (String author : authors) {
            System.out.println(author);
        }
    }
}

三、使用总结
1. 使用JSONPath.reader方法读取inputStream的时候,只能读取一次,再次读取的时候会导致异常;
2. JSONPath跟Xpath算是难兄难弟吧,JSONPath算是模拟XPath的一个翻版吧。

四、参考链接
1. JSONPath-简单入门
2. JsonPath的使用

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值