RestController中的Spring SCALA返回列表

问题描述 投票:1回答:1

如何在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
}
json spring scala rest serialization
1个回答
3
投票

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]

© www.soinside.com 2019 - 2024. All rights reserved.