java.io.ByteArrayInputStream抛出No Serializer found异常,配置后未解决求助
问题根因
报错是因为Jackson序列化框架没有内置java.io.ByteArrayInputStream类的序列化规则,你返回的接口响应对象中包含该类型的字段时,序列化过程就会抛出该异常。你之前配置的FAIL_ON_EMPTY_BEANS = false仅能解决空类无序列化字段的报错,无法处理缺省序列化器的场景。
解决方案
- 方案1(推荐):避免直接返回流对象到接口层
流本身是不可重复读取的资源,序列化传输没有实际业务意义,建议先将ByteArrayInputStream转换为字节数组或者Base64字符串后再放入返回对象:
// 示例:流转字节数组 ByteArrayInputStream inputStream = getYourInputStream(); byte[] streamBytes = inputStream.readAllBytes(); // 将streamBytes替换原有的inputStream字段放入返回DTO
如果是文件下载场景,直接使用Spring内置的资源响应方式即可,不需要自定义DTO封装流:
@GetMapping("/download") public ResponseEntity<Resource> download() { ByteArrayInputStream inputStream = getYourInputStream(); byte[] bytes = inputStream.readAllBytes(); ByteArrayResource resource = new ByteArrayResource(bytes); return ResponseEntity.ok() .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=test.file") .contentType(MediaType.APPLICATION_OCTET_STREAM) .body(resource); }
- 方案2:自定义序列化器
如果确实有业务需要保留ByteArrayInputStream类型的字段,可以自行为Jackson注册该类型的序列化器:
- 编写自定义序列化实现类
public class ByteArrayInputStreamSerializer extends StdSerializer<ByteArrayInputStream> { public ByteArrayInputStreamSerializer() { super(ByteArrayInputStream.class); } @Override public void serialize(ByteArrayInputStream value, JsonGenerator gen, SerializerProvider serializers) throws IOException { // 自定义序列化规则,示例为转换为Base64字符串输出 byte[] bytes = value.readAllBytes(); gen.writeString(Base64.getEncoder().encodeToString(bytes)); } }
- 将序列化器注册到ObjectMapper中
@Bean public ObjectMapper objectMapper() { ObjectMapper objectMapper = new ObjectMapper(); // 注册自定义序列化器 SimpleModule module = new SimpleModule(); module.addSerializer(ByteArrayInputStream.class, new ByteArrayInputStreamSerializer()); objectMapper.registerModule(module); // 保留原有配置 objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); return objectMapper; }
内容的提问来源于stack exchange,提问作者Advaid
相关产品推荐
相关产品推荐

