Spring RestClient如何将接口返回的数组反序列化为CustomType对象的集合
Spring RestClient如何将接口返回的数组反序列化为CustomType对象的集合
嘿,这个问题我之前也碰到过,其实Spring RestClient提供了很简单的解决办法,不用再处理那些烦人的LinkedHashMap啦!
你现在的问题根源是Java的类型擦除机制:直接传ArrayList.class的时候,序列化工具没办法识别你要的是ArrayList<CustomType>,只能默认把数组元素转成LinkedHashMap集合。下面给你两种靠谱的解决方式:
方法一:使用ParameterizedTypeReference直接获取List
Spring专门提供了ParameterizedTypeReference类,它能通过匿名内部类的方式保留泛型的类型信息,让默认的Jackson序列化器能正确把数组元素转成CustomType对象。代码示例如下:
import org.springframework.web.client.RestClient; import org.springframework.core.ParameterizedTypeReference; import java.util.List; // ... 其他业务代码 RestClient restClient = RestClient.create(); return restClient.get() .uri(url) .header("Authorization", token) .retrieve() .body(new ParameterizedTypeReference<List<CustomType>>() {});
用这个方式调用后,会直接返回List<CustomType>类型的结果,里面的每个元素都是你需要的CustomType实例,不用再做手动转换。
方法二:先反序列化为CustomType数组再转集合
如果你更习惯操作数组,或者想灵活控制集合类型,也可以直接指定数组类型CustomType[].class,之后再转成List:
import org.springframework.web.client.RestClient; import java.util.ArrayList; import java.util.Arrays; import java.util.List; // ... 其他业务代码 RestClient restClient = RestClient.create(); CustomType[] customTypeArray = restClient.get() .uri(url) .header("Authorization", token) .retrieve() .body(CustomType[].class); // 转成支持增删操作的可变ArrayList List<CustomType> customTypeList = new ArrayList<>(Arrays.asList(customTypeArray)); return customTypeList;
这里要注意,Arrays.asList()返回的是固定大小的列表,如果你的业务需要对集合做增删操作,一定要再包装成新的ArrayList。
这两种方法都能完美解决你的问题,选哪种就看你的代码习惯啦!
备注:内容来源于stack exchange,提问作者Ajant
相关产品推荐
相关产品推荐

