将从 API 收到的响应数据导入 CSV 文件

Import Response Data received from an API into CSV file

我正在尝试使用 Rest Assured 将从 API 响应中获取的数据存储到 CSV 文件中。 这就是我的代码的样子:

public void Test_01() throws Exception {
    Response response = RestAssured.given() // enter valid credentials
            .get("https://gorest.co.in/public-api/users")
            .then()
            .extract()
            .response();

    String data = response.jsonPath().get("data");

    System.out.println(response.asString().getClass());
    try
    {
        JsonNode jsonTree = new ObjectMapper().readTree(data);
        CsvSchema.Builder csvSchemaBuilder = CsvSchema.builder();
        JsonNode firstObject = jsonTree.elements().next();
        firstObject.fieldNames().forEachRemaining(fieldName -> {csvSchemaBuilder.addColumn(fieldName);} );
        CsvSchema csvSchema = csvSchemaBuilder.build().withHeader();
        CsvMapper csvMapper = new CsvMapper();
        csvMapper.writerFor(JsonNode.class)
                .with(csvSchema)
                .writeValue(new File("src/main/resources/lmsget.csv"), jsonTree);

    }   catch(Exception ex)

    {
        throw ex;
    }
}

当我尝试执行此测试时,出现错误:Schema specified that header line is to be written; but contains no column names。也许,这是因为 JSON 的格式,它看起来像:

"code": 200,
"meta": {
"pagination": {
"total": 2610,
"pages": 131,
"page": 1,
"limit": 20
}

之后,出现一个包含对象的数组 data。我只想存储该数据。 我还在 JsonPath:

中尝试了一些提取响应的更改
Object data = response.JsonPath.get("data");

但是当我在 JsonNode jsonTree = new ObjectMapper().readTree(data); 中使用它时出现错误:

com.fasterxml.jackson.core.JsonParseException: Unexpected character ('i' (code 105)): was expecting double-quote to start field name
at [Source: (String)"[{id=2583, name=Aryan Shah, email=shah_aryan@oreilly.biz, gender=male, status=inactive},

解决方案:

  • 第 1 步:将响应转换为字符串格式的 json
  • 第 2 步:由 Jackson 提取数组 data,而不是 Rest-Assured
String res = given()
                .get("https://gorest.co.in/public-api/users")
                .asString();
try {
     JsonNode jsonTree = new ObjectMapper().readTree(res).get("data");
     ...
}