【问题标题】:How to return JSON instead of Case Class in akka-Http如何在akka-Http中返回JSON而不是Case Class
【发布时间】:2019-08-21 14:03:18
【问题描述】:

我创建了一个路由以流式传输 JSON 中的案例类列表。但如果我使用 ByteString,则会打印案例类而不是 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 而不是案例类

【问题讨论】:

  • 为什么不能将案例类转换为 JSON?

标签: json scala akka-stream akka-http


【解决方案1】:

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

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

希望对你有帮助

PS:好的可能是你要发送到那里的 HTTP 代码

【讨论】:

    【解决方案2】:

    考虑到您已经在使用 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)
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-09-22
      • 1970-01-01
      • 1970-01-01
      • 2023-04-05
      • 2022-01-18
      • 2020-04-25
      • 2022-01-01
      相关资源
      最近更新 更多