JsonPath工具類封裝

書接上文和上上文:

在經歷過一些波折之后,總算是把JsonPath工具類的封裝類寫好了,時間倉促。沒有太嚴格的測試,等有機會我再用Groovy進行單元測試框架spock寫一些單測來驗證一下。

工具類的語言Groovy,有點不必多說了,相信使用Java技術棧的同學讀起來應該不會有障礙。另外我把官方的API當做類注釋寫出來了。

有兩個關于verify類的方法,這個主要是為了驗證用的,涉及到Groovy重載操作符,是專門寫的一個提供給Groovy腳本的驗證功能類,還有就是為開源測試服務增加功能儲備。

代碼如下:

package com.fun.utils

import com.alibaba.fastjson.JSONObject
import com.fun.base.exception.ParamException
import com.fun.frame.SourceCode
import com.jayway.jsonpath.JsonPath
import com.jayway.jsonpath.JsonPathException
import org.slf4j.Logger
import org.slf4j.LoggerFactory

/**下面是例子,官方文檔地址:https://github.com/json-path/JsonPath/blob/master/README.md
 * $.store.book[*].author   The authors of all books
 * $..author    All authors
 * $.store.*    All things, both books and bicycles
 * $.store..price   The price of everything
 * $..book[2]   The third book
 * $..book[-2]  The second to last book
 * $..book[0,1] The first two books
 * $..book[:2]  All books from index 0 (inclusive) until index 2 (exclusive)
 * $..book[1:2] All books from index 1 (inclusive) until index 2 (exclusive)
 * $..book[-2:] Last two books
 * $..book[2:]  Book number two from tail
 * $..book[?(@.isbn)]   All books with an ISBN number
 * $.store.book[?(@.price < 10)]    All books in store cheaper than 10
 * $..book[?(@.price <= $['expensive'])]    All books in store that are not "expensive"
 * $..book[?(@.author =~ /.*REES/i)]    All books matching regex (ignore case)
 * $..* Give me every thing
 * $..book.length() The number of books
 *
 *
 * min()    Provides the min value of an array of numbers   Double
 * max()    Provides the max value of an array of numbers   Double
 * avg()    Provides the average value of an array of numbers   Double
 * stddev() Provides the standard deviation value of an array of numbers    Double
 * length() Provides the length of an array Integer
 * sum()    Provides the sum value of an array of numbers   Double
 * min()    最小值 Double
 * max()    最大值 Double
 * avg()    平均值 Double
 * stddev() 標準差 Double
 * length() 數組長度    Integer
 * sum()    數組之和    Double
 * ==   left is equal to right (note that 1 is not equal to '1')
 * !=   left is not equal to right
 * <    left is less than right
 * <=   left is less or equal to right
 * >    left is greater than right
 * >=   left is greater than or equal to right
 * =~   left matches regular expression [?(@.name =~ /foo.*?/i)]
 * in   left exists in right [?(@.size in ['S', 'M'])]
 * nin  left does not exists in right
 * subsetof 子集 [?(@.sizes subsetof ['S', 'M', 'L'])]
 * anyof    left has an intersection with right [?(@.sizes anyof ['M', 'L'])]
 * noneof   left has no intersection with right [?(@.sizes noneof ['M', 'L'])]
 * size size of left (array or string) should match right
 * empty    left (array or string) should be empty
 */
class JsonUtil extends SourceCode {

    private static Logger logger = LoggerFactory.getLogger(JsonUtil.class)

    /**
     * 用戶構建對象,獲取verify對象
     */
    private JSONObject json

    private JsonUtil(JSONObject json) {
        this.json = json
    }

    static JsonUtil getInstance(JSONObject json) {
        new JsonUtil(json)
    }

    Verify getVerify(String path) {
        Verify.getInstance(this.json, path)
    }

    /**
     * 獲取string對象
     * @param path
     * @return
     */
    String getString(String path) {
        def object = get(path)
        object == null ? EMPTY : object.toString()
    }


    /**
     * 獲取int類型
     * @param path
     * @return
     */
    int getInt(String path) {
        changeStringToInt(getString(path))
    }

    /**
     * 獲取boolean類型
     * @param path
     * @return
     */
    int getBoolean(String path) {
        changeStringToBoolean(getString(path))
    }

    /**
     * 獲取long類型
     * @param path
     * @return
     */
    int getLong(String path) {
        changeStringToLong(getString(path))
    }
    
    /**
     * 獲取double類型
     * @param path
     * @return
     */
    double getDouble(String path) {
        changeStringToDouble(getString(path))
    }

    /**
     * 獲取list對象
     * @param path
     * @return
     */
    List getList(String path) {
        get(path) as List
    }

    /**
     * 獲取匹配對象,類型傳參
     * 這里不加public  IDE會報錯
     * @param path
     * @param tClass
     * @return
     */
    public <T> T getT(String path, Class<T> tClass) {
        try {
            get(path) as T
        } catch (ClassCastException e) {
            logger.warn("類型轉換失敗!", e)
            null
        }
    }

    /**
     * 獲取匹配對象
     * @param path
     * @return
     */
    Object get(String path) {
        logger.debug("匹配對象:{},表達式:{}", json.toString(), path)
        if (json == null || json.isEmpty()) ParamException.fail("json為空或者null,參數錯誤!")
        try {
            JsonPath.read(this.json, path)
        } catch (JsonPathException e) {
            logger.warn("jsonpath:{}解析失敗,json值", json.toString(), path, e)
            null
        }
    }


}


  • 公眾號FunTester首發(fā),更多原創(chuàng)文章:460+原創(chuàng)文章,歡迎關注、交流,禁止第三方擅自轉載。

熱文精選

?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內容