我必须使用RestTemplate
的REST API,它不会遵循良好的模式,例如使用HTTP状态代码。
我有以下两个回复内容。
{
"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"
}}
我们可以注意到一个地图结构,如下所示::
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."
}
如何映射Java类以解决这两种情况?
答案 0 :(得分:1)
如果没有,您可以先将其反序列化为Map<String, JsonNode>
,然后根据status
字段的存在情况,将其反序列化为相应的类型:
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);
}
答案 1 :(得分:0)
您可以使用属性Map<String, MyObject> myObjects
创建新的Response类,并将status
和message
添加到Response类,不要忘记使用@JsonIgnoreProperties(ignoreUnknown = true)
进行批注。
但是,你从RestTemplate&#34; json可能不会自动序列化到myObjects
的json,你可能需要对响应进行一些格式化,以适应下面的响应类。
@JsonIgnoreProperties(
ignoreUnknown = true
)
public class Response{
Map<String, MyObject> myObjects;
String status;
String message;
}