如何使用多个响应内容映射RestTemplate?

时间:2017-11-14 20:28:07

标签: java spring rest jackson

我必须使用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;

MyObject Class

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类以解决这两种情况?

2 个答案:

答案 0 :(得分:1)

嗯...... API很糟糕,你能让他们改变它吗?至少要使用正确的HTTP代码?

如果没有,您可以先将其反序列化为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类,并将statusmessage添加到Response类,不要忘记使用@JsonIgnoreProperties(ignoreUnknown = true)进行批注。 但是,你从RestTemplate&#34; json可能不会自动序列化到myObjects的json,你可能需要对响应进行一些格式化,以适应下面的响应类。

@JsonIgnoreProperties(
    ignoreUnknown = true
)
public class Response{
  Map<String, MyObject> myObjects;
  String status;
  String message;
}