I have various versions on my API. So, for example, I have the accept header as center_1.1. When I pass this header with a previous version of the payload I would like to throw an exception, showing the user that the path is wrong. So, for example, for version center_1.0, the payload should be as follows:
{
"data": {
"city": "Campinas",
...
}
}
And for payload of version center_1.1, should be:
{
"data": {
"route": "Campinas",
...
}
}
When I send for example, the header as center_1.1 and the payload of version 1.0, I would like to give the user an error, showing that data.city path is wrong.
I've tried making this:
public <T extends ... > void validateExpectedPayloadVersion(JsonApi<T> payload, String version)
throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(payload);
oos.flush();
oos.close();
InputStream is = new ByteArrayInputStream(baos.toByteArray());
try (InputStreamReader streamReader = new InputStreamReader(is, StandardCharsets.UTF_8)) {
JsonApi<T> payloadRequest;
try {
payloadRequest= unmarshallToVersion(streamReader, version);
} catch (final UnrecognizedPropertyException e) {
final String offendingPath = StringUtils
.join(e.getPath().stream().map(JsonMappingException.Reference::getFieldName)
.collect(
Collectors.toList()), ".");
throw new InvalidException(offendingPath);
}
}
}
private <T extends ...> JsonApi<T> unmarshallToVersion(final InputStreamReader inputStreamReader,
final String version)
throws IOException {
final ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
mapper.enable(SerializationFeature.INDENT_OUTPUT);
switch (version) {
case "center.1.0":
return (JsonApi<T>) mapper.readValue(inputStreamReader, new TypeReference<JsonApi<CenterDtoV0>>() {});
case "center.1.1":
default:
return (JsonApi<T>) mapper.readValue(inputStreamReader, new TypeReference<JsonApi<CenterDtoV1>>() {});
}
}
But this won't throw the desired exception (UnrecognizedPropertyException).