I'm using rest-assured and twitter4j for testing twitter API.
All calls are made via RestAssured, twitter4j is used for Json response deserialization.
And what I want to do is to deserialize Json response from twitter - GET statuses/home_timeline
which returns Array of Status objects(from twitter4j).
I can easily deserialize one Status object like here:
@Test
public void verifyTwitCreation() {
RequestSpecification spec = new RqBuilder()
.withStatus(textToPublish)
.build();
Response response = twitClient.createTwit(spec);
assertResponseCode(response, 200);
String json = response.getBody().asString();
Status status = null;
try {
status = TwitterObjectFactory.createStatus(json);
} catch (TwitterException e) {
e.printStackTrace();
}
System.out.println(status.toString());
}
But I don't know how to do the same for deserializing array of such Status objects.
Try extracting a list of statuses using JsonPath and then parse them using TwitterObjectFactory
:
Response response = twitClient.createTwit(spec);
List<Map<Object, Object>> responseList = response.jsonPath().getList("$");
ObjectMapper mapper = new ObjectMapper();
List<Status> statuses = responseList.stream().map(s -> {
Status status = null;
try {
String json = mapper.writeValueAsString(s)
status = TwitterObjectFactory.createStatus(json);
} catch (TwitterException | IOException e) {
e.printStackTrace();
}
return status;
}).collect(Collectors.toList());
You could move try/catch during parsing to a separate method so it looks nicer:
public class TestClass {
@Test
public void verifyTwitCreation() {
RequestSpecification spec = new RqBuilder()
.withStatus(textToPublish)
.build();
Response response = twitClient.createTwit(spec);
List<Map<Object, Object>> responseList = response.jsonPath().getList("$");
List<Status> statuses = responseList.stream().map(TestClass::createStatus)
.collect(Collectors.toList());
}
private static Status createStatus(Map<Object, Object> jsonMap) {
Status status = null;
ObjectMapper mapper = new ObjectMapper();
try {
String json = mapper.writeValueAsString(jsonMap);
status = TwitterObjectFactory.createStatus(json);
} catch (TwitterException | IOException e) {
e.printStackTrace();
}
return status;
}
}
Update: Since JsonPath getList() returns list of maps we should convert all maps to JSON string so that it can be used by TwitterObjectFactory. Jackson's ObjectMapper is used in example, but any JSON parsing tool can be used.