Reputation: 214
I must consume a REST API with RestTemplate
which doesn't follows good patterns, like using HTTP status codes, for example.
I have both below response contents.
{
"435": {
"Codigo": "435",
"Tipo": "",
"Corretor": "62",
"Cliente": "48304",
"DataHora": "2016-04-27 14:18:24",
"DataHoraAtualizacao": "",
"Assunto": "Visita - Imóvel 2",
"Local": "",
"Texto": "",
"DataHoraInicio": "2016-04-28 12:00:00",
"DataHoraFinal": "2016-04-28 12:20:00"
},
"687": {
"Codigo": "687",
"Tipo": "",
"Corretor": "20",
"Cliente": "33040",
"DataHora": "2016-07-18 17:09:28",
"DataHoraAtualizacao": "",
"Assunto": "Visita - Imóvel 2",
"Local": "",
"Texto": "teste",
"DataHoraInicio": "2016-07-28 08:00:00",
"DataHoraFinal": "2016-07-28 09:00:00"
}}
We can note a map structure, as follows::
Map<String, MyObject> myObjects;
public class MyObject {
@JsonProperty("Codigo")
private String codigo;
@JsonProperty("Tipo")
private String tipo;
@JsonProperty("Corretor")
private String corretor;
@JsonProperty("Cliente")
private String cliente;
@JsonProperty("DataHora")
private String dataHora;
@JsonProperty("DataHoraAtualizacao")
private String dataHoraAtualizacao;
@JsonProperty("Assunto")
private String assunto;
@JsonProperty("Local")
private String local;
@JsonProperty("Texto")
private String texto;
@JsonProperty("DataHoraInicio")
private String dataHoraInicio;
@JsonProperty("DataHoraFinal")
private String dataHoraFinal;
}
{
"status": "200",
"message": "A pesquisa não retornou resultados."
}
How I should map a Java class in order to solve both cases?
Upvotes: 1
Views: 2584
Reputation: 7058
um... that API is awful, can you ask them to change it? at least to use proper HTTP codes?
If not, you could deserialize first into a Map<String, JsonNode>
and then depending on the presence of the status
field, deserialize into the appropriate type:
String json = ...
Map<String, JsonNode> response = mapper.readValue(json, ...);
if (response.get("status") != null) {
// its an error, deserialize into Error type
Error error = mapper.readValue(json, Error.class);
else {
// not an error, deserialize into MyObject
MyObject obj = mapper.readValue(json, MyObject.class);
}
Upvotes: 1
Reputation: 1
You can create a new Response class with a property Map<String, MyObject> myObjects
and add status
and message
to the Response class, don't forget to annotate with @JsonIgnoreProperties(ignoreUnknown = true)
.
However the json you get back from RestTemplate "might"not automatically serialize to myObjects
, you might need to do a little formatting with the response to fit your Response Class below.
@JsonIgnoreProperties(
ignoreUnknown = true
)
public class Response{
Map<String, MyObject> myObjects;
String status;
String message;
}
Upvotes: 0