Spring RestClient, чтобы десериализовать (извлечь) между двумя совершенно разными типамиJAVA

Программисты JAVA общаются здесь
Ответить
Anonymous
 Spring RestClient, чтобы десериализовать (извлечь) между двумя совершенно разными типами

Сообщение Anonymous »

Существует сторонняя API REST, который я не контролирую, которая обнаруживает конечную точку.{
"device": "sensor-01",
"temperature": 23.5
}
< /code>
Однако, если есть ошибка на стороне API, она все равно будет возвращать HTTP 200, с таким корпусом, как это: < /p>
{
"message": "An error occurred",
"code": 400
}
< /code>
Опять же, я не контролирую этот API и не могу изменить это поведение.public record GoodPojo(String device, float temperature) {
}
< /code>
public record BadPojo(String message, int code) {
}
< /code>
However, it seems there is nothing common between the two objects. It is hard to find a common object, a common parent between the two.
And for the REST call, I am doing this.
public String question() {
var result = restClient.get()
.uri("https://the-api.com")
.retrieve()
.body(GoodPojo.class);

return result.toString();
}
< /code>
This works for the good object, but the bad object cannot be converted like this.
Is there a way in Spring to do something like:
public String question() {
var result = restClient.get()
.uri("https://the-api.com")
.retrieve()
.body(GoodPojo.class | BadPojo.class); //convert into the first one, and if you cannot, convert into the second one

return result.toString();
}
< /code>
Without having to try to convert this into a good object, and catch the exception, if it fails, to convert to the other object manually?
Basically, how to convert the HTTP response into different types possible?

Подробнее здесь: https://stackoverflow.com/questions/797 ... ferent-typ
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «JAVA»