gpt4 book ai didi

java - 如何将RestTemplate映射为多个响应内容?

转载 作者:行者123 更新时间:2023-11-30 06:25:28 25 4
gpt4 key购买 nike

我必须使用带有 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 结构,如下所示::

Map<String, MyObject> myObjects;

MyObject 类

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

最佳答案

嗯...那个 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);
}

关于java - 如何将RestTemplate映射为多个响应内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47294619/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com