json - 如何使用 Jackson 序列化带有多个参数构造函数的 scala 对象?

标签 json scala serialization jackson

class AgentResponse[T] @JsonCreator()(@JsonProperty("result") val result: T, @JsonProperty("status") val status: ResponseStatus)

class ResponseStatus @JsonCreator()(@JsonProperty("succeeded") val succeeded: Boolean, @JsonProperty("message") val message: String, @JsonProperty("timeStamp") val timeStamp: Long)

new ObjectMapper().registerModule(DefaultScalaModule).writer().writeValue(out, new AgentResponse(result, new ResponseStatus(true, "OK", now)))

它抛出错误:

JsonMappingException: No serializer found for class com.fg.mail.smtp.rest.Handler$AgentResponse and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationConfig.SerializationFeature.FAIL_ON_EMPTY_BEANS) )

scala 对象应该是什么样子才能按预期工作?

最佳答案

引用自scala.annotation.meta :

By default, annotations on (val-, var- or plain) constructor parameters end up on the parameter, not on any other entity. Annotations on fields by default only end up on the field.

The meta-annotations in package scala.annotation.meta are used to control where annotations on fields and class parameters are copied. This is done by annotating either the annotation type or the annotation class with one or several of the meta-annotations in this package.

因此注释转到构造函数参数。您需要将其分配给 getter 以及构造函数参数:

class MyClass @JsonCreator() (@(JsonProperty @getter @param) val arg: String)

关于json - 如何使用 Jackson 序列化带有多个参数构造函数的 scala 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17616672/

相关文章:

java - 与 Java BigDecimal 比较 null BigDecimal

Scala Future.fold 不见了?

java - 使用 Play 框架格式化 View 中的 ValidationError

c# - 如何最小化序列化数据的大小

javascript - 如何使用来自 AJAX 调用的 JSON 数据构建表格?

java - 在 Java/Clojure 中将 UTF-32 编码的字符串(C 样式)转换为 UTF-16(JSON 样式)编码的字符串

json - Golang - 使用/遍历 JSON 解析映射

javascript - Node.js - 使用 async.waterfall 进行依赖 API 请求调用,并使用 underscore.extend 合并 JSON 响应

c# - C# 继承类Stream并且可以序列化的Stream

java - 序列化 - 需要手动定义 SerialVersionUID?