Akka中Jackson无法反序列化普通类,求无注解序列化方案
Akka Jackson-JSON 无注解序列化问题解决
问题描述
尝试使用Akka内置的jackson-json序列化器反序列化Actor命令时,发现实现Command接口的CreateExample类必须添加@JsonCreator、@JsonProperty注解才能正常序列化,而官方文档说明多数普通类无需额外注解即可完成序列化。现寻求无需添加注解的序列化解决方案。
相关代码
Java类代码
package org.example; // ... class ExampleAR extends EventSourcedBehaviorWithEnforcedReplies<ExampleAR.Command, ExampleAR.Event, ExampleAR.State> { // ... interface Command { /* 空接口 */ } public static class CreateExample implements Command { final SecurityClaims claims; final ExampleRef ref; final String title; final ActorRef<StatusReply<ExampleCreated>> replyTo; public CreateExample( SecurityClaims claims, ExampleRef ref, String title, ActorRef<StatusReply<ExampleCreated>> replyTo) { this.claims = claims; this.ref = ref; this.title = title; this.replyTo = replyTo; } } // ... }
配置文件(application.conf)
akka.actor { serialization-bindings { "org.example.ExampleAR$Command" = jackson-json } }
报错信息
java.lang.IllegalArgumentException: Command [org.example.ExampleAR$CreateExample@20251fb0] isn't serializable., ... Caused by: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `org.example.ExampleAR$CreateExample` (no Creators, like default constructor, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
解决方法
1. 编译时保留参数名称(核心步骤)
Jackson需要获取构造函数的参数名称才能自动匹配JSON字段,Java 8+需在编译时添加-parameters选项,让编译器保留参数名信息:
- Maven配置:
<build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.1</version> <configuration> <source>11</source> <!-- 替换为你的Java版本 --> <target>11</target> <compilerArgs> <arg>-parameters</arg> </compilerArgs> </configuration> </plugin> </plugins> </build> - Gradle配置:
tasks.withType(JavaCompile) { options.compilerArgs.add('-parameters') }
2. 开启Akka Jackson的自动检测配置
在application.conf中添加Jackson序列化的额外配置,启用参数名称模块和构造函数自动检测:
akka.actor { serialization-bindings { "org.example.ExampleAR$Command" = jackson-json } serialization-jackson { parameter-names-module = on auto-detect-constructors = on } }
3. 确保依赖完整性
确认项目已引入Akka的jackson-json序列化模块,该模块已包含Jackson参数名称相关依赖:
- Maven依赖:
<dependency> <groupId>com.typesafe.akka</groupId> <artifactId>akka-serialization-jackson_2.13</artifactId> <version>2.8.5</version> <!-- 替换为你的Akka版本 --> </dependency>
4. 检查内部类访问权限
确保CreateExample是静态内部类(当前代码已满足),非静态内部类会导致Jackson无法正常实例化,需调整为static修饰。
内容的提问来源于stack exchange,提问作者gervais.b
相关产品推荐
相关产品推荐

