如何在Sprint @RestController中返回SCALA列表或序列。列表返回值未正确序列化。
结果是:
[GET] http://localhost:9090/devices
{"empty":false,"traversableAgain":true}
我是否需要导入Jackson ObjectMapper com.fasterxml.jackson
才能在列表中获得正确的REST get result序列化?
我的RestController看起来像这样:
@RestController
class DeviceController {
var devices = Set[Device]()
@RequestMapping(value = Array("/devices"), method = Array(RequestMethod.GET))
def accounts() : List[Device] = devices.toList
}
Spring没有考虑到SCALA的设计 - 因此它无法正确处理SCALA列表。它也不能处理Seq [Device]。
只需使用SCALA JavaConverters包即可轻松将SCALA列表转换为JAVA列表。
import scala.collection.JavaConverters._
@RestController
class DeviceController {
var devices = Set[Device]()
@RequestMapping(value = Array("/devices"), method = Array(RequestMethod.GET))
def accounts() : java.util.List[Device] = {
devices.toList.asJava
}
}
结果将是:
[GET] http://localhost:9090/devices
[{"name":"first device"},{"name":"second device"}]
请记住将结果类型更改为:java.util.List[Device]