使用jsonpath解析json内容

官网链接:https://github.com/jayway/JsonPath

JsonPath提供的json解析非常强大,它提供了类似正则表达式的语法,基本上可以满足所有你想要获得的json内容。下面我把官网介绍的每个表达式用代码实现,可以更直观的知道该怎么用它。

一.首先需要依赖的jar包

二.因为编译的时候会报log4j的警报,所以需要在项目的src目录下新建log4j.properties文件,内容如下:

log4j.rootLogger=WARN, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n

三.准备一个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
            },
            {
                "category": "fiction",
                "author": "Herman Melville",
                "title": "Moby Dick",
                "isbn": "0-553-21311-3",
                "price": 8.99
            },
            {
                "category": "fiction",
                "author": "J. R. R. Tolkien",
                "title": "The Lord of the Rings",
                "isbn": "0-395-19395-8",
                "price": 22.99
            }
        ],
        "bicycle": {
            "color": "red",
            "price": 19.95
        }
    },
    "expensive": 10
}

四.我们从代码中分析用法,代码如下

package com.jsonpath;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import net.minidev.json.JSONArray;

import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.ReadContext;

/**
 * @author QiaoJiafei
 * @version 创建时间:2016年3月2日 下午3:37:42
 * 类说明
 */
public class TestJsonPath {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String sjson = readtxt();
        //String sjson = "{\"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},{\"category\": \"fiction\",\"author\": \"Herman Melville\",\"title\": \"Moby Dick\",\"isbn\": \"0-553-21311-3\",\"price\": 8.99},{\"category\": \"fiction\",\"author\": \"J. R. R. Tolkien\",\"title\": \"The Lord of the Rings\",\"isbn\": \"0-395-19395-8\",\"price\": 22.99}],\"bicycle\": {\"color\": \"red\",\"price\": 19.95}},\"expensive\": 10}";

        print("--------------------------------------getJsonValue0--------------------------------------");
        getJsonValue0(sjson);
        print("--------------------------------------getJsonValue1--------------------------------------");
        getJsonValue1(sjson);
        print("--------------------------------------getJsonValue2--------------------------------------");
        getJsonValue2(sjson);
        print("--------------------------------------getJsonValue3--------------------------------------");
        getJsonValue3(sjson);
        print("--------------------------------------getJsonValue4--------------------------------------");
        getJsonValue4(sjson);

        print("--------------------------------------getJsonValue--------------------------------------");
        getJsonValue(sjson);
    }

    private static String readtxt() {
        // TODO Auto-generated method stub
        StringBuilder sb = new StringBuilder();
        try {
            FileReader fr = new FileReader("D:/workspace/PressureTest/json.txt");
            BufferedReader bfd = new BufferedReader(fr);
            String s = "";
            while((s=bfd.readLine())!=null) {
                sb.append(s);
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println(sb.toString());
        return sb.toString();
    }

    private static void getJsonValue(String json) {
        //The authors of all books
        List<String> authors1 = JsonPath.read(json, "$.store.book[*].author");

        //All authors
        List<String> authors2 = JsonPath.read(json, "$..author");

        //All things, both books and bicycles //authors3返回的是net.minidev.json.JSONArray
        List<Object> authors3 = JsonPath.read(json, "$.store.*");

        //The price of everything
        List<Object> authors4 = JsonPath.read(json, "$.store..price");

        //The third book
        List<Object> authors5 = JsonPath.read(json, "$..book[2]");

        //The first two books
        List<Object> authors6 = JsonPath.read(json, "$..book[0,1]");

        //All books from index 0 (inclusive) until index 2 (exclusive)
        List<Object> authors7 = JsonPath.read(json, "$..book[:2]");

        //All books from index 1 (inclusive) until index 2 (exclusive)
        List<Object> authors8 = JsonPath.read(json, "$..book[1:2]");

        //Last two books
        List<Object> authors9 = JsonPath.read(json, "$..book[-2:]");

        //Book number two from tail
        List<Object> authors10 = JsonPath.read(json, "$..book[2:]");

        //All books with an ISBN number
        List<Object> authors11 = JsonPath.read(json, "$..book[?(@.isbn)]");

        //All books in store cheaper than 10
        List<Object> authors12 = JsonPath.read(json, "$.store.book[?(@.price < 10)]");

        //All books in store that are not "expensive"
        List<Object> authors13 = JsonPath.read(json, "$..book[?(@.price <= $[‘expensive‘])]");

        //All books matching regex (ignore case)
        List<Object> authors14 = JsonPath.read(json, "$..book[?(@.author =~ /.*REES/i)]");

        //Give me every thing
        List<Object> authors15 = JsonPath.read(json, "$..*");

        //The number of books
        List<Object> authors16 = JsonPath.read(json, "$..book.length()");
        print("**************authors1**************");
        print(authors1);
        print("**************authors2**************");
        print(authors2);
        print("**************authors3**************");
        printOb(authors3);
        print("**************authors4**************");
        printOb(authors4);
        print("**************authors5**************");
        printOb(authors5);
        print("**************authors6**************");
        printOb(authors6);
        print("**************authors7**************");
        printOb(authors7);
        print("**************authors8**************");
        printOb(authors8);
        print("**************authors9**************");
        printOb(authors9);
        print("**************authors10**************");
        printOb(authors10);
        print("**************authors11**************");
        printOb(authors11);
        print("**************authors12**************");
        printOb(authors12);
        print("**************authors13**************");
        printOb(authors13);
        print("**************authors14**************");
        printOb(authors14);
        print("**************authors15**************");
        printOb(authors15);
        print("**************authors16**************");
        printOb(authors16);

    }

    private static void getJsonValue0(String json) {
        // TODO Auto-generated method stub
        List<String> authors = JsonPath.read(json, "$.store.book[*].author");
        //System.out.println(authors.size());
        print(authors);

    }
    private static void getJsonValue1(String json) {
        Object document = Configuration.defaultConfiguration().jsonProvider().parse(json);

        String author0 = JsonPath.read(document, "$.store.book[0].author");
        String author1 = JsonPath.read(document, "$.store.book[1].author");
        print(author0);
        print(author1);

    }

    private static void getJsonValue2(String json) {
        ReadContext ctx = JsonPath.parse(json);

        List<String> authorsOfBooksWithISBN = ctx.read("$.store.book[?(@.isbn)].author");

        List<Map<String, Object>> expensiveBooks = JsonPath
                                    .using(Configuration.defaultConfiguration())
                                    .parse(json)
                                    .read("$.store.book[?(@.price > 10)]", List.class);
        print(authorsOfBooksWithISBN);
        print("****************Map****************");
        printListMap(expensiveBooks);
    }

    private static void getJsonValue3(String json) {
        //Will throw an java.lang.ClassCastException
        //List<String> list = JsonPath.parse(json).read("$.store.book[0].author");
        //由于会抛异常,暂时注释上面一行,要用的话,应使用下面的格式

        //Works fine
        String author = JsonPath.parse(json).read("$.store.book[0].author");
        print(author);
    }

    private static void getJsonValue4(String json) {
        List<Map<String, Object>> books1 =  JsonPath.parse(json)
                .read("$.store.book[?(@.price < 10 && @.category == ‘fiction‘)]");
        List<Map<String, Object>> books2 =  JsonPath.parse(json)
                .read("$.store.book[?(@.category == ‘reference‘ || @.price > 10)]");
        print("****************books1****************");
        printListMap(books1);
        print("****************books2****************");
        printListMap(books1);
    }

    private static void print(List<String> list) {
        for(Iterator<String> it = list.iterator();it.hasNext();) {
            System.out.println(it.next());
        }
    }

    private static void printOb(List<Object> list) {
        for(Iterator<Object> it = list.iterator();it.hasNext();) {
            System.out.println(it.next());
        }
    }

    private static void printListMap(List<Map<String, Object>> list) {
        for(Iterator<Map<String, Object>> it = list.iterator();it.hasNext();) {
            Map<String, Object> map = it.next();
            print("****");
            for(Iterator iterator =map.entrySet().iterator();iterator.hasNext();) {
                System.out.println(iterator.next());
            }

        }
    }

    private static void print(String s) {
        System.out.println(s);
    }

}

1.首先我们看getJsonValue()这个方法的输出结果:

--------------------------------------getJsonValue--------------------------------------
**************authors1**************
Nigel Rees
Evelyn Waugh
Herman Melville
J. R. R. Tolkien
**************authors2**************
Nigel Rees
Evelyn Waugh
Herman Melville
J. R. R. Tolkien
**************authors3**************
[{"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},{"category":"fiction","author":"Herman Melville","title":"Moby Dick","isbn":"0-553-21311-3","price":8.99},{"category":"fiction","author":"J. R. R. Tolkien","title":"The Lord of the Rings","isbn":"0-395-19395-8","price":22.99}]
{color=red, price=19.95}
**************authors4**************
8.95
12.99
8.99
22.99
19.95
**************authors5**************
{category=fiction, author=Herman Melville, title=Moby Dick, isbn=0-553-21311-3, price=8.99}
**************authors6**************
{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}
**************authors7**************
{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}
**************authors8**************
{category=fiction, author=Evelyn Waugh, title=Sword of Honour, price=12.99}
**************authors9**************
{category=fiction, author=Herman Melville, title=Moby Dick, isbn=0-553-21311-3, price=8.99}
{category=fiction, author=J. R. R. Tolkien, title=The Lord of the Rings, isbn=0-395-19395-8, price=22.99}
**************authors10**************
{category=fiction, author=Herman Melville, title=Moby Dick, isbn=0-553-21311-3, price=8.99}
{category=fiction, author=J. R. R. Tolkien, title=The Lord of the Rings, isbn=0-395-19395-8, price=22.99}
**************authors11**************
{category=fiction, author=Herman Melville, title=Moby Dick, isbn=0-553-21311-3, price=8.99}
{category=fiction, author=J. R. R. Tolkien, title=The Lord of the Rings, isbn=0-395-19395-8, price=22.99}
**************authors12**************
{category=reference, author=Nigel Rees, title=Sayings of the Century, price=8.95}
{category=fiction, author=Herman Melville, title=Moby Dick, isbn=0-553-21311-3, price=8.99}
**************authors13**************
{category=reference, author=Nigel Rees, title=Sayings of the Century, price=8.95}
{category=fiction, author=Herman Melville, title=Moby Dick, isbn=0-553-21311-3, price=8.99}
**************authors14**************
{category=reference, author=Nigel Rees, title=Sayings of the Century, price=8.95}
**************authors15**************
{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},{"category":"fiction","author":"Herman Melville","title":"Moby Dick","isbn":"0-553-21311-3","price":8.99},{"category":"fiction","author":"J. R. R. Tolkien","title":"The Lord of the Rings","isbn":"0-395-19395-8","price":22.99}], bicycle={color=red, price=19.95}}
10
[{"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},{"category":"fiction","author":"Herman Melville","title":"Moby Dick","isbn":"0-553-21311-3","price":8.99},{"category":"fiction","author":"J. R. R. Tolkien","title":"The Lord of the Rings","isbn":"0-395-19395-8","price":22.99}]
{color=red, price=19.95}
{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}
{category=fiction, author=Herman Melville, title=Moby Dick, isbn=0-553-21311-3, price=8.99}
{category=fiction, author=J. R. R. Tolkien, title=The Lord of the Rings, isbn=0-395-19395-8, price=22.99}
reference
Nigel Rees
Sayings of the Century
8.95
fiction
Evelyn Waugh
Sword of Honour
12.99
fiction
Herman Melville
Moby Dick
0-553-21311-3
8.99
fiction
J. R. R. Tolkien
The Lord of the Rings
0-395-19395-8
22.99
red
19.95
**************authors16**************
4

2.然后看getJsonValue0()、getJsonValue1()、getJsonValue2()、getJsonValue3()、getJsonValue4()的输出结果

--------------------------------------getJsonValue0--------------------------------------
Nigel Rees
Evelyn Waugh
Herman Melville
J. R. R. Tolkien
--------------------------------------getJsonValue1--------------------------------------
Nigel Rees
Evelyn Waugh
--------------------------------------getJsonValue2--------------------------------------
Herman Melville
J. R. R. Tolkien
****************Map****************
****
category=fiction
author=Evelyn Waugh
title=Sword of Honour
price=12.99
****
category=fiction
author=J. R. R. Tolkien
title=The Lord of the Rings
isbn=0-395-19395-8
price=22.99
--------------------------------------getJsonValue3--------------------------------------
Nigel Rees
--------------------------------------getJsonValue4--------------------------------------
****************books1****************
****
category=fiction
author=Herman Melville
title=Moby Dick
isbn=0-553-21311-3
price=8.99
****************books2****************
****
category=fiction
author=Herman Melville
title=Moby Dick
isbn=0-553-21311-3
price=8.99
时间: 2024-10-12 07:31:35

使用jsonpath解析json内容的相关文章

安卓解析json,使用BaseAdapter添加至ListView中,中间存储用JavaBean来实现

这是一个小练习,要求解析一个提供的json文件.并将其中的id,title值获取,以ListView形式展示出来.(开发工具是android studio) 下面开始: 首先我想到的是先把json文件内容读进一个String类型的变量中去保存,然后再对字符串进行解析.Id和title可以看做为一组数据,然后整个文件有很多组数据,所以创建了 1 ArrayList<HashMap> ArrayList=new ArrayList<>(); list中保存所有条数据,需要时再获取.所以

C#深入解析Json格式内容

继上一篇<浅谈C#手动解析Json格式内容>我又来分析加入了一些功能让 这个解析类更实用 本章节最会开放我最终制作成功的Anonymous.Json.dll这个解析库 需要的拿走~ 功能继上一篇增加了许多上一篇只是讲述了  解析的步骤但是 至于一些扩展的功能却没有涉及 本文将继续讲解 1.如何将json转换为一个类或者结构 甚至属性 2.如何将一个类或者结构甚至属性转换为json 就这两点就已经很头疼了 诶 废话不多说进入正题 上一篇一直有个很神秘的JsonObject没有讲解 现在先来揭开J

浅谈C#手动解析Json格式内容

这个应该算处女贴吧 - - 之前百度了许久基本没有一个满意的json结构的解析类库 想了想还是自己做一个吧 现在我来说下大概的思路 首先我创建了一个 JsonTokener的类 用于处理json字符串的一些操作里面有个枚举 1 public enum JsonCharType 2 { 3 BeginObject = 123, //{ 4 EndObject = 125, //} 5 BeginArray = 91, //[ 6 EndArray = 93, //] 7 DoubleQuote =

在QML应用中使用JSONListModel来帮我们解析JSON数据

我们知道JSON数据在很多web service中被广泛使用.它在我以前的文章中都有被提到: - 如何读取一个本地Json文件并查询该文件展示其内容 - 如何在QML应用中使用Javascript解析JSON 在今天的这篇文章中,我来介绍一种类似像XmlListModel(解析XML)的方法来解析我们的JSON.这个方法更加简单直接.关于JSONListModel的介绍可以参照地址https://github.com/kromain/qml-utils. 我们今天就利用JSONListModel

pyspider示例代码二:解析JSON数据

本系列文章主要记录和讲解pyspider的示例代码,希望能抛砖引玉.pyspider示例代码官方网站是http://demo.pyspider.org/.上面的示例代码太多,无从下手.因此本人找出一下比较经典的示例进行简单讲解,希望对新手有一些帮助. 示例说明: pyspider爬取的内容通过回调的参数response返回,response有多种解析方式.1.response.json用于解析json数据2.response.doc返回的是PyQuery对象3.response.etree返回的

js中eval详解,用Js的eval解析JSON中的注意点

先来说eval的用法,内容比较简单,熟悉的可以跳过eval函数接收一个参数s,如果s不是字符串,则直接返回s.否则执行s语句.如果s语句执行结果是一个值,则返回此值,否则返回undefined. 需要特别注意的是对象声明语法“{}”并不能返回一个值,需要用括号括起来才会返回值,简单示例如下: var s1='"a" + 2'; //表达式var s2='{a:2}'; //语句alert(eval(s1)); //->'a2'alert(eval(s2)); //->und

解析JSON格式数据

 别想一下造出大海,必须先由小河川开始. 本讲内容:解析JSON格式数据 1)比起XML,JSON的主要优势在于它的体积更小,在网络上传输的时候可以更省流量.但缺点在于,它的语义性较差,看起来不如XML直观. 2)解析JSON格式的数据有多种方式,常用的两种是:使用官方提供的JSONObject和谷歌的开源库GSON. 示例一:解析服务器返回的数据 一.JSONObject解析方式 步骤: 1.在服务器中定义一个JSONArray,并将服务器返回的数据传入到JSONArray对象中 2.循环

QT开发(六十二)———QT5解析Json文件

QT开发(六十二)---QT5解析Json文件 一.QT5 Json简介 QT4中使用第三方库QJson解析JSON文件. QT5新增加了处理JSON的类,类均以QJson开头,包含在QtCore模块中.QT5新增加六个相关类: QJsonArray 封装 JSON 数组 QJsonDocument 读写 JSON 文档 QJsonObject 封装 JSON 对象 QJsonObject::iterator 用于遍历QJsonObject的STL风格的非const遍历器 QJsonParseE

【转】C# 解析JSON方法总结

http://blog.csdn.net/jjhua/article/details/51438317 主要参考http://blog.csdn.NET/joyhen/article/details/24805899和http://www.cnblogs.com/yanweidie/p/4605212.html 根据自己需求,做些测试.修改.整理. 使用Newtonsoft.Json 一.用JsonConvert序列化和反序列化. 实体类不用特殊处理,正常定义属性即可,控制属性是否被序列化参照高