Es gibt eine REST-API von Drittanbietern, über die ich keine Kontrolle habe, die einen Endpunkt enthüllt.{
"device": "sensor-01",
"temperature": 23.5
}
< /code>
Wenn jedoch ein Fehler auf der API -Seite vorliegt, würde es immer noch HTTP 200 mit einem Körper wie folgt zurückgeben: < /p>
{
"message": "An error occurred",
"code": 400
}
< /code>
Ich habe erneut keine Kontrolle über diese API und kann dieses Verhalten nicht ändern.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?
Federruhe, um sich zwischen zwei völlig unterschiedlichen Typen zu deverialisieren (abrufen) ⇐ Java
-
- Similar Topics
- Replies
- Views
- Last post