I'm trying to store a data taken from the API response into CSV file using Rest Assured
.
That's how my code looks like:
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;
}
}
When I try to execute this test, I am getting an error: Schema specified that header line is to be written; but contains no column names
. Maybe, that's because of the format of the JSON, which looks like:
"code": 200,
"meta": {
"pagination": {
"total": 2610,
"pages": 131,
"page": 1,
"limit": 20
}
After that, comes an array data
with objects in it. I just want to store that data only.
I've also tried some changes in extracting response as JsonPath
:
Object data = response.JsonPath.get("data");
But when I use it in JsonNode jsonTree = new ObjectMapper().readTree(data);
I am getting error:
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 protected], gender=male, status=inactive},
CodePudding user response:
Solution:
- Step 1: Convert response to json in String format
- Step 2: Extract array
data
by Jackson, not Rest-Assured
String res = given()
.get("https://gorest.co.in/public-api/users")
.asString();
try {
JsonNode jsonTree = new ObjectMapper().readTree(res).get("data");
...
}