【发布时间】:2020-10-21 19:40:06
【问题描述】:
我在 Scala 项目中使用 Spring Boot,并且我已经使用 Json4s 对 JSON 进行序列化和反序列化。到目前为止,我一直在编写这样的端点:
@RequestMapping(path = Array("/getSomething"), produces = Array(MediaType.APPLICATION_JSON_VALUE))
def getSomething: String = {
// do some things
val resultValue: ResultType = ??? // where ResultType is some case class that can be serialized with json4s
json4s.native.Serialization.write(resultValue)
}
但是,我真的希望能够避免最后一步,同时更清楚端点的返回类型是什么。此外,我希望能够提取返回类型以生成 API 文档。所以相反,我想写同样的东西:
@RequestMapping(path = Array("/getSomething"), produces = Array(MediaType.APPLICATION_JSON_VALUE))
def getSomething: ResultType = {
// do some things
resultValue
}
然而,当我这样做时,结果总是{}。我认为这是因为 Spring 使用的是 Jackson 而不是 Json4s,而且我没有注释用于 Jackson 的案例类。我要做的就是添加一些在每个端点上调用的拦截器,并将结果转换为 JSON 字符串。编写拦截器很容易(只需json4s.native.Serialization.write),但我如何注册它才能让 Spring 每次都自动使用它?
【问题讨论】:
-
注意:Json4s 是 vulnerable under DoS/DoW attacks!
标签: spring scala jackson json4s