我正在尝试使用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");
...
}