gpt4 book ai didi

scala - 为 Play Framework http 响应创建可写 [Argonaut.Json]

转载 作者:行者123 更新时间:2023-12-01 02:12:14 26 4
gpt4 key购买 nike

我正在尝试使用这样的 Play json 库更改此函数的实现

def apply[T](action: => ApiResponse[T])(implicit tjs: Writes[T], ec: ExecutionContext): Future[Result] = {
action.fold(
err =>
Status(err.statusCode) {
JsObject(Seq(
"status" -> JsString("error"),
"statusCode" -> JsNumber(err.statusCode),
"errors" -> Json.toJson(err.errors)
))
},
t =>
Ok {
JsObject(Seq(
"status" -> JsString("ok"),
"response" -> Json.toJson(t)
))
}
)
}

像这样使用 argonaut
def apply[T](action: => ApiResponse[T])(implicit encodeJson: EncodeJson[T], ec: ExecutionContext): Future[Result] = {
action.fold(
err =>
Status(err.statusCode) {
Json(
"status" -> jString("error"),
"statusCode" -> jNumber(err.statusCode),
"errors" -> err.errors.asJson
)
},
t =>
Ok {
Json(
"status" -> jString("ok"),
"response" -> t.asJson
)
}
)
}

但我明白了

Cannot write an instance of argonaut.Json to HTTP response. Try to define a Writeable[argonaut.Json]



对于 Status{} 块和 Ok{} 块,我在这里得到了有关此问题的有用答案 https://groups.google.com/forum/#!topic/play-framework/vBMf72a10Zc

所以我尝试像这样创建隐式转换
implicit def writeableOfArgonautJson(implicit codec: Codec): Writeable[Json] = {
Writeable(jsval => codec.encode(jsval.toString))
}

我认为将 json 对象转换为字符串并将其提供给 codec.encode 应该将其转换为 Array[Bytes] 但我得到

Cannot guess the content type to use for argonaut.Json. Try to define a ContentTypeOf[argonaut.Json]



jsval.nospaces.getBytes 也返回 Array[Bytes] 所以我不知道这是否可以用来帮助

所以虽然我认为最后一条错误消息意味着我只需要告诉 play 它应该使用内容类型 application.json 我也觉得这可能是一个不必要的兔子洞,应该有一个更简单的方法来做到这一点。

编辑:它不是一个兔子洞,因为定义 contentType 至少可以编译一些东西,但我仍然想知道这是否正确

最佳答案

您似乎已经回答了您自己的问题,但要确认的是 Writable[A]是:

  • 如何转换类型 AArray[Bytes]
  • 在响应中使用什么内容类型,这也需要
  • 当前字符编码

  • 字符编码由隐式 Codec 处理。实例,所以你需要一个隐含的 ContentTypeOf[A]哪里 Aargonaunt.Json :
    implicit def contentTypeOf_ArgonautJson(implicit codec: Codec): ContentTypeOf[argonaut.Json] = {
    ContentTypeOf[argonaut.Json](Some(ContentTypes.JSON))
    }

    然后是 Writable[A] ,其中有一个 type constraintA有一个范围内 ContentTypeOf[A] (您刚刚定义的):
    implicit def writeableOf_ArgonautJson(implicit codec: Codec): Writeable[argonaut.Json] = {
    Writeable(jsval => codec.encode(jsval.toString))
    }

    正如你所指出的,兔子洞就到此为止了。事实上,当您考虑现在可以只做 Ok(myArgonautObject) 时,这确实看起来有点分散,但没有太多额外的代码。在不需要进一步转换和标题设置样板的情况下,您可以根据需要执行任意数量的操作。

    也许你可以把这些隐含在 ExtraJsonHelpers 中trait 并将其混合到您的 Controller 中,以减少更多样板。

    关于scala - 为 Play Framework http 响应创建可写 [Argonaut.Json],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28263677/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com