欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

JSONPath小试牛刀之Snack3

程序员文章站 2022-05-31 22:19:22
最近在网上看了些 的入门例子。打算用 这个框架写写例子。 对`JSON的处理绝对是神器。 1.准备JSON字符串 2.Meven 依赖 3.示例代码 4.控制台打印结果 ......

最近在网上看了些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