REST新手求助:如何获取响应根层级外的数据?
如何在JsonPath中获取根层级外的数据?
嘿,刚接触REST和JsonPath的时候碰到这种问题太正常啦!你已经知道用setRoot()来简化重复路径的写法,但要访问根层级或者当前root之外的数据其实很简单,有两种常见的处理方式:
方式一:直接使用完整JSON路径访问
当你设置了root之后,它只是作为默认的路径前缀——如果你需要访问不在这个root下的节点,直接写完整的JSON路径就能覆盖默认前缀。比如针对你给出的响应:
{ "StatusCode": 200, "Result": { "CustomerStuff": { "Name": "John", "State": "Oregon", "GetEmail": false }, "eText": "Will only get paper mail. " } }
你可以这样获取根层级的StatusCode,或者Result下的eText:
String responseBody = given().body().when().etc...; JsonPath jsonPath = new JsonPath(responseBody).setRoot("Result.CustomerStuff"); // 获取CustomerStuff内的数据(用root简化路径) String customerName = jsonPath.getString("Name"); String customerState = jsonPath.getString("State"); // 获取根层级的StatusCode(用完整路径) int statusCode = jsonPath.getInt("StatusCode"); // 获取Result下的eText(用完整路径) String eText = jsonPath.getString("Result.eText");
方式二:创建多个JsonPath实例(适合多场景复用)
如果需要频繁在不同的路径层级间切换,建议创建多个JsonPath实例,每个对应不同的root,这样代码会更清晰:
String responseBody = given().body().when().etc...; // 专门处理CustomerStuff的实例 JsonPath customerPath = new JsonPath(responseBody).setRoot("Result.CustomerStuff"); String name = customerPath.getString("Name"); boolean getEmail = customerPath.getBoolean("GetEmail"); // 专门处理根层级和Result其他数据的实例 JsonPath globalPath = new JsonPath(responseBody); int statusCode = globalPath.getInt("StatusCode"); String eText = globalPath.getString("Result.eText");
简单来说,setRoot()只是帮你少写重复的路径前缀,并不会限制你访问其他节点——只要写出完整的路径,就能拿到任何层级的数据啦!
内容的提问来源于stack exchange,提问作者Anton
相关产品推荐
相关产品推荐

