You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Micronaut Serialization如何将单个值视为数组反序列化?

解决Micronaut Serialization兼容单个对象/数组反序列化的问题

问题场景

调用第三方API时,某个字段的返回格式不一致:数据量为多个时返回数组,仅一个时返回单个对象。将JSON反序列化为POJO的List字段时,触发Unexpected token START_OBJECT, expected START_ARRAY错误。Jackson可通过@JsonFormat(with = JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY)处理该场景,但Micronaut Serialization不支持该注解,需寻找无需自定义反序列化类的解决方案。

原错误POJO示例:

@Serdeable.Deserializable
public class Response {
   private List<Package> package;
}

API返回数组格式:

{
  "package": [
    {},
    {},
    {}
  ]
}

API返回单个对象格式:

{
  "package": {}
}

触发的错误日志:

DEBUG io.micronaut.http.client.jdk.HttpResponseAdapter Error decoding body for type [...] from 'application/json;charset=UTF-8'. Attempting fallback.
DEBUG io.micronaut.http.client.jdk.HttpResponseAdapter CodecException Message was: Error decoding stream for type [class ...]: Error decoding property [...] of type [class ...]: Error decoding property [List ...] of type [class ...]: Error decoding property [List ...] of type [class ...]: Unexpected token START_OBJECT, expected START_ARRAY  at [Source: (byte[]) ..."

解决方案

在目标List字段上添加@Serdeable.Deserializable(acceptSingleValueAsArray = true)注解,即可让Micronaut Serialization自动将单个对象转换为包含该对象的List,无需编写自定义反序列化类。

修改后的POJO示例:

@Serdeable.Deserializable
public class Response {
    @Serdeable.Deserializable(acceptSingleValueAsArray = true)
    private List<Package> package;

    // 补充必要的构造器、Getter/Setter方法
}

原理说明

该注解会告知Micronaut反序列化器:当遇到与字段类型(List)不匹配的单个对象时,自动将其包装为长度为1的List,从而兼容两种返回格式,避免类型不匹配的错误。

内容的提问来源于stack exchange,提问作者Simon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 20:22:44