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);
//结果:$.store.book.title = ["高效Java","研磨设计模式","重构","虚拟机"]

        // 获取json中所有title的值
        titles = (List) JSONPath.read(json, "$..title");
        System.out.println("$..title = " + titles);
//结果:$..title = [高效Java, 研磨设计模式, 重构, 虚拟机]

        // 获取json中book数组中包含isbn的所有值
        List isbns = (List) JSONPath.read(json, "$.store.book[?(@.isbn)]");
        System.out.println("$.store.book[?(@.isbn)] = " + isbns);
//结果:$.store.book[?(@.isbn)] = [{"title":"重构","price":8,"isbn":"553"},{"title":"虚拟机","price":22,"isbn":"395"}]

        // 获取json中book数组中price<10的所有值
        List prices = (List) JSONPath.read(json, "$.store.book[?(@.price < 10)]");
        System.out.println("$.store.book[?(@.price < 10)] = " + prices);
//结果:$.store.book[?(@.price < 10)] = [{"title":"重构","price":8,"isbn":"553"}]

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

        // 获取json中store下所有price的值
        prices = (List) JSONPath.read(json, "$.store..price");
        System.out.println("$.store..price = " + prices);
//结果:$.store..price = [10, 12, 8, 22, 19]

        // 获取json中book数组的前两个区间值
        List books = (List) JSONPath.read(json, "$.store.book[:2]");
        System.out.println("$.store.book[:2] = " + books);
//结果:$.store.book[:2] = [{"title":"高效Java","price":10}, {"title":"研磨设计模式","price":12}, {"title":"重构","price":8,"isbn":"553"}]

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

    }

} 
  

 

你可能感兴趣的:(Java基础)