如何在akka-Http中返回JSON而不是Case Class

问题描述 投票:0回答:2

我创建了一个路由来流式传输JSON中的案例类列表。但是如果我使用ByteString,则打印case类而不是JSON

def streamRoute: Route = pathEndOrSingleSlash {
        val byteString = new LocalFileParser(config).importFromFiles.map(phoneNumber => ByteString(phoneNumber.toString + "\n"))
        complete(HttpEntity(ContentTypes.`application/json`, byteString))
    }
   // RESULT: PhoneNumber(+35799000123,Some(357),Some(Cyprus),Some(Cytamobile-Vodafone),Some(MOBILE))

如果我只使用complete(new LocalFileParser(config).importFromFiles),那么这就是给我JSON。第二种方法是否适用于流式分组响应?如果不是,我如何修复第一个方法来返回JSON而不是Case Class

json scala akka-stream akka-http
2个回答
0
投票

使用Json.toJson(result)方法,您可以将结果作为JSON发送,

在你的情况下像这样:val byteString = new LocalFileParser(config).importFromFiles.map(phoneNumber => Ok(Json.toJson(phoneNumber)))

希望这可以帮助

PS:好的可能就是你要发送的HTTP代码


0
投票

考虑到您已经在使用Circe,可以通过将此库添加到项目中来简化:

"de.heikoseeberger" %% "akka-http-circe" % "<latest-version>"

并导入这两个类,以便将你的List[PhoneNumber]编组为包含json的HttpResponse

import de.heikoseeberger.akkahttpcirce.ErrorAccumulatingCirceSupport._
import io.circe.generic.auto._

def streamRoute: Route = pathEndOrSingleSlash {
  complete(new LocalFileParser(config).importFromFiles)
}
© www.soinside.com 2019 - 2024. All rights reserved.