fastjson(十)JSONPath 的使用(二)

要解析的 json:

{
  "store": {
    "book": [
      {
        "title": "高效Java",
        "price": 10
      },
      {
        "title": "研磨设计模式",
        "price": 12
      },
      {
        "title": "重构",
        "isbn": "553",
        "price": 8
      },
      {
        "title": "虚拟机",
        "isbn": "395",
        "price": 22
      }
    ],
    "bicycle": {
      "color": "red",
      "price": 19
    }
  }
}

测试类:

package json.fastjson.jsonpath;

import java.util.List;

import com.alibaba.fastjson.JSONPath;

public class TestJSONPath2 {

    @SuppressWarnings("unchecked")
    public static void main(String[] args) {
        String json = "{\"store\":{\"book\":[{\"title\":\"高效Java\",\"price\":10},{\"title\":\"研磨设计模式\",\"price\":12},{\"title\":\"重构\",\"isbn\":\"553\",\"price\":8},{\"title\":\"虚拟机\",\"isbn\":\"395\",\"price\":22}],\"bicycle\":{\"color\":\"red\",\"price\":19}}}";

        // 获取json中store下book下的所有title值
        List titles = (List) JSONPath.read(json, "$.store.book.title");
        System.out.println("$.store.book.title = " + titles);

        // 获取json中所有title的值
        titles = (List) JSONPath.read(json, "$..title");
        System.out.println("$..title = " + titles);

        // 获取json中book数组中包含isbn的所有值
        List isbns = (List) JSONPath.read(json, "$.store.book[?(@.isbn)]");
        System.out.println("$.store.book[?(@.isbn)] = " + isbns);

        // 获取json中book数组中price<10的所有值
        List prices = (List) JSONPath.read(json, "$.store.book[?(@.price < 10)]");
        System.out.println("$.store.book[?(@.price < 10)] = " + prices);

        // 获取json中book数组中的title等于“高效Java”的对象
        titles = (List) JSONPath.read(json, "$.store.book[?(@.title = '高效Java')]");
        System.out.println("$.store.book[?(@.title = '高效Java')] = " + titles);

        // 获取json中store下所有price的值
        prices = (List) JSONPath.read(json, "$.store..price");
        System.out.println("$.store..price = " + prices);

        // 获取json中book数组的前两个区间值
        List books = (List) JSONPath.read(json, "$.store.book[:2]");
        System.out.println("$.store.book[:2] = " + books);

        // 获取书个数
        int size = (int) JSONPath.read(json, "$.store.book.size()");
        System.out.println("$.store.book.size() = " + size);

    }

}
 
  

输出结果:

$.store.book.title = ["高效Java","研磨设计模式","重构","虚拟机"]
$..title = [高效Java, 研磨设计模式, 重构, 虚拟机]
$.store.book[?(@.isbn)] = [{"title":"重构","price":8,"isbn":"553"},{"title":"虚拟机","price":22,"isbn":"395"}]
$.store.book[?(@.price < 10)] = [{"title":"重构","price":8,"isbn":"553"}]
$.store.book[?(@.title = '高效Java')] = [{"title":"高效Java","price":10}]
$.store..price = [10, 12, 8, 22, 19]
$.store.book[:2] = [{"title":"高效Java","price":10}, {"title":"研磨设计模式","price":12}, {"title":"重构","price":8,"isbn":"553"}]
$.store.book.size() = 4

你可能感兴趣的:(FastJSON)