JSONPath小试牛刀之Snack3

2022-10-12,,

最近在网上看了些jsonpath的入门例子。打算用snack3这个框架写写例子。json path对`json的处理绝对是神器。

1.准备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
        }
    }
}

2.meven 依赖

<dependency>
  <groupid>org.noear</groupid>
  <artifactid>snack3</artifactid>
  <version>3.1.5.3</version>
</dependency>

3.示例代码

@test
public void demo1() {
    string 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}}}";

    onode n = onode.load(json);

    map map = n.select("$.store.book[0]").toobject(map.class);

    system.out.println("category: " + map.get("category"));
    system.out.println("author: " + map.get("author"));
    system.out.println("title: " + map.get("title"));
    system.out.println("price: " + map.get("price"));

    system.out.println("========================");
   
    list<string> list = n.select("$.store.book[*].author").toobject(list.class);
    for (string author : list) {
        system.out.println(author);
    }

    //java bean 泛型输出,此处不打印了
    list<bookmodel> list2 = n.select("$.store.book")
                             .toobject((new arraylist<bookmodel>(){}).getclass());
}

4.控制台打印结果

category: reference
author: nigel rees
title: sayings of the century
price: 8.95
========================
nigel rees
evelyn waugh

《JSONPath小试牛刀之Snack3.doc》

下载本文的Word格式文档,以方便收藏与打印。