PlayフレームワークコントローラーがボイラープレートなしでJSONとオブジェクト(ケースクラス)の間で自動的に変換できるかどうか疑問に思っています。
SpringMVCとTwitterのFinatraがそれを行うことができるように。以下は、Finatraフレームワークのコードです。
@Singleton
class TweetsController @Inject()(
tweetsService: TweetsService)
extends Controller {
post("/tweet") { requestTweet: TweetPostRequest =>
// requestTweet is a case class mapping json request
tweetsService.save(requestTweet)
...
}
get("/tweet/:id") { request: TweetGetRequest =>
// case class mapping json response
tweetsService.getResponseTweet(request.id)
...
}
}
ただし、Play Frameworkの場合、JSON会話を手動で行う必要があります。Playは、暗黙的に使用せずに方法をサポートできますか?
Playがそれをサポートできない理由、または将来のリリースでサポートする理由はありますか?
この目的のために、次のユーティリティクラスを使用します
/**
* Framework method for handling a request that takes a Json body as a parameter. If the JSON body can be
* parsed as a valid instance of `A` , the resulting object is passed into the body which is expected
* to produce a Result.
*
*
* Note that it is not necessary to create the Action object in the body of the supplied handler; this is
* done for you.
*
* @tparam A A case class that the input JSON should be parsed into.
* @param body The body of the handler for this request. This must be a function that will take an instance of `A`
* and use it generate a `Result`.
*
*/
def handleJsonRequest[A : Reads](body: A => Result) = Action(parse.json) { request =>
request.body.validate[A].map {body}.recoverTotal {
errors: JsError =>
throw new ...(errors)
}
}
これをハンドラーで次のように使用できます
def handleGet() = handleJsonRequest[Body] {body =>
...
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加