美文网首页
JSONPath 提取对象属性值

JSONPath 提取对象属性值

作者: Tinyspot | 来源:发表于2023-11-09 09:42 被阅读0次

    1. JSONPath

    • 官方文档 https://github.com/alibaba/fastjson/wiki/JSONPath

    1.1 基础知识

    • $表示根
    • 语法:$.element (注:路径表达式区分大小写)
    • 嵌套查询 $.parentElement.element

    2. JSONPath 示例

    @Test
    public void demo() {
        OrderDTO orderDTO = new OrderDTO("1001", "20230101001", 0);
        // 不加 $ 也行,等价 $.orderCode
        JSONPath compile = JSONPath.compile("orderCode");
        System.out.println(compile.eval(orderDTO));
    }
    

    3. 获取属性值

    @Test
    public void pathValue() {
        OrderDTO orderDTO = new OrderDTO("1001", "20230101001", 0);
        String extendCondition = "fields=orderCode, orderStatus, tradeId;";
    
        // 解析
        Map<String, String> params = new HashMap<>();
        if (extendCondition.trim().contains(";")) {
            String[] conditionArray = extendCondition.trim().split(";");
            for (String item : conditionArray) {
                if (StringUtils.isNotEmpty(item) && item.contains("=")) {
                    params.put(item.split("=")[0].trim(), item.split("=")[1].trim());
                }
            }
        }
    
        String orderFields = Optional.ofNullable(params.get("fields"))
                .filter(StringUtils::isNotEmpty)
                .orElse("$.orderCode, $.orderStatus, $.tradeId");
    
        List<JSONPath> jsonPaths = Splitter.on(",").trimResults().omitEmptyStrings()
                .splitToList(orderFields)
                .stream()
                .map(JSONPath::compile)
                .collect(Collectors.toList());
    
        String orderInfo = Joiner.on(",").skipNulls().join(jsonPaths.stream()
                .map(jsonPath -> jsonPath.eval(orderDTO))
                .map(obj -> {
                    if (obj instanceof String) {
                        return (String)obj;
                    } else {
                        return String.valueOf(obj);
                    }
                })
                .collect(Collectors.toList()));
    
        System.out.println(orderInfo);
    }
    

    相关文章

      网友评论

          本文标题:JSONPath 提取对象属性值

          本文链接:https://www.haomeiwen.com/subject/mbscwdtx.html