基于Fitnesse的接口自动化测试-关键字设计-样例-通过路径在json串中获取值

需求

之前给出过从Json中获取指定值的样例。
当在Fitnesse中处理复杂结构的json串时,就比较麻烦了,所以这里提供一种更加简便的方式。

实现

主要利用Fastjson的JSONPath来实现

<dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.9</version>
</dependency>

1.编写构造函数和成员变量

    private String content;
    public StringFixture() {
    }

    public StringFixture(String content) {
        this.content = content;
    }

2.实现方法(关键字)

 public String getValueByFieldPath(String fieldPath) {
        String jsonContent = this.content;
        return JsonUtil.getValueByFieldPath(jsonContent,fieldPath);
    }

public static String getValueByFieldPath(String jsonContent, String fieldPath) {
        try {
            if (StringUtils.isBlank(jsonContent)) {
                return "json串为空";
            }
            if (StringUtils.isBlank(fieldPath)) {
                return "字段路径为空";
            }
            try {
                JSONObject.parseObject(jsonContent);
            } catch (Exception e) {
                return "json串格式异常";
            }
            Object result = JSONPath.read(jsonContent, fieldPath);
            return String.valueOf(result);
        } catch (Exception e) {
            return e.toString();
        }
    }

使用

1.引入类对应package

|import         |
|own.slim.string|

2.编写脚本

json串样例

!define content {!-{"field":"value","list":[{"p":0,"h":"1","i":898989},{"p":1,"h":"like777","i":"000000"},{"p":2,"h":"","i":787878}],"map":{"m1":{"m2":{"m3":9,"m4":["0","1","2"]}}}}-!}

|script|string fixture     |${content}              |
|note  |直接获取对象                                      |
|show  |getValueByFieldPath|$.list[0]               |
|note  |获取对象的一个属性值                                  |
|show  |getValueByFieldPath|$.list[0].p             |
|note  |获取对象的一个属性值                                  |
|show  |getValueByFieldPath|$.field                 |
|note  |获取两个对象的某个属性值                                |
|show  |getValueByFieldPath|$.list[0,1].p           |
|note  |获取连续几个对象的某个属性值                              |
|show  |getValueByFieldPath|$.list[0:2].p           |
|note  |获取对象列表中的某个属性的所有值                            |
|show  |getValueByFieldPath|$.list['i']             |
|note  |获取对象列表中的多个属性的所有值                            |
|show  |getValueByFieldPath|$.list['i','p']         |
|note  |在列表中 获取属性p=0对象的某个属性值                        |
|show  |getValueByFieldPath|$.list[p=0].i           |
|note  |在列表中 获取属性h匹配like%对象的某个属性值                   |
|show  |getValueByFieldPath|$.list[h like 'like%'].i|
|note  |获取对象的一个列表数据                                 |
|show  |getValueByFieldPath|$.map.m1.m2.m4[2]       |

3.测试

getValueByKeyFromJsonString

总结

使用JSONPath,除了可以应对复杂json串外,它还提供了过滤功能。
例如上面例子中
$.list[p=0].i ,意思是在list中找到p等于0的map,然后在该map中输出i的值。

参考

关于路径的写法,可以参考下面的链接
https://www.php.cn/java/java-fastjson-jsonpath.html

posted @ 2021-08-25 09:50  月色深潭  阅读(122)  评论(0)    收藏  举报