【问题标题】:how to handle spring rest service call returning multiple type responses如何处理返回多种类型响应的spring rest服务调用
【发布时间】:2018-08-13 17:39:49
【问题描述】:

我正在尝试通过 spring 的 rest 调用调用第三方 api。目前我正在使用 postforobject。我正在将请求类转换为字符串并为对象调用帖子。响应被视为字符串,然后将其转换为类。已使用以下参数定义了类

Class responseDto {
 private Arraylist < Response > response;
 getResponse();
 setResponse();
}

Response {
  String code;
  String trid;
  Getters();
  Setters();
}

我正在使用 Jackson 依赖项进行序列化和反序列化。 此类对于以下响应工作正常

{
"response":[
   {
     "code":"100",
     "trid":"123"
   }
 ]
}

但在错误情况下,其余部分返回一个具有相同名称“响应”的 json 类,如下所示

{
 "response":{
  "code":"700",
  "trid":"123"
 }
}

并且我用一些 json 映射异常定义的类的反序列化失败(com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token)。那么我该如何解决java spring 中的这个问题。

【问题讨论】:

  • 你在检查我的答案吗

标签: java json spring rest jackson


【解决方案1】:

解决方案 1:使用@JsonFormat(> 2.6 版本)

只需使用 @JsonFormat 将您的字段注释为

import java.util.List;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonFormat.Feature;

public class ResponseDto {

    @JsonFormat(with = Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY)
    private List<Response> response;

    public List<Response> getResponse() {
        return response;
    }

    public void setResponse(List<Response> response) {
        this.response = response;
    }
}

解决方案 2:设置反序列化功能

public static void main(String[] args) throws IOException {

    ObjectMapper mapper = new ObjectMapper();

    // global setting, can be overridden using @JsonFormat in beans
    // when using @JsonFormat on fields, then this is not needed 
    mapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);

    ResponseDto dto =  mapper.readValue(stringResponse, ResponseDto.class);
}

现在 json 中包含单个对象、单个对象数组、多个对象数组的 response 节点将被成功解析为 Response 对象的列表。

【讨论】:

    猜你喜欢
    • 2018-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-20
    • 1970-01-01
    • 2020-07-11
    • 1970-01-01
    • 2015-07-26
    • 2022-01-13
    相关资源
    最近更新 更多