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 对象应该是什么样子才能按预期工作?
最佳答案
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/