首页 > 解决方案 > RestAssured JsonPath 到字符串

问题描述

有没有办法将整个 JSON 路径数据转换为 Java 中的字符串?

我正在研究 API,它们的响应采用 JSON 格式。通过 Postman/WireShark 很容易理解 JSON 结构,但我试图通过 Java 运行 API 请求,获取响应,将原始响应转换为 JSON,将 JSON 响应转换为字符串格式并打印出来。'.getString()' 方法是访问特定元素而不是整个数据。方法 '.toString()' 也不适用于 JSON 数据。

    JsonPath json = (ConvertRawFiles.rawtoJSON(response));
    String id   = json.get("id");
    log.info("The id is " + id);

    JsonPath json = (ConvertRawFiles.rawtoJSON(response));
    String complete_json_data   = ???;
    log.info("The complete json data is " + complete_json_data);

提到的代码片段“???” 是我想要达到的目标。

标签: javajsonstringrest-assured

解决方案


可以将 JsonPath 对象转换为 String 的方法有:

JsonPath json = (ConvertRawFiles.rawtoJSON(response));
String complete_json_data = json.prettify();

JsonPath json = (ConvertRawFiles.rawtoJSON(response));
String complete_json_data = json.prettyPrint();

推荐阅读