Skip to content

Instantly share code, notes, and snippets.

@takkkun
Last active March 24, 2017 05:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save takkkun/d4c880da66309dcb361751fd80710b2f to your computer and use it in GitHub Desktop.
Save takkkun/d4c880da66309dcb361751fd80710b2f to your computer and use it in GitHub Desktop.
case class JsonRpcBody[P <: Product](jsonrpc: String, method: String, params: P, id: String)
case class SampleParams(_1: String, _2: Int) extends Product2[String, Int]
// JsonRpcBody[SampleParams] にデコードするためには、DecodeJson[JsonRpcBody[SampleParams]] を
// 定義する必要がある。しかし、SampleParams 以外にも増えるのは予想され、その度に DecodeJson[JsonRpcBody[OtherParams]] などを
// 書くと大変めんどう。params の解釈の仕方が違うだけなのに、jsonrpc, method, id の部分も解釈しなきゃだし。
// と言うわけで以下のように書く。
implicit def jsonRpcBodyDecodeJson[P <: Product](implicit paramsDecodeJson: DecodeJson[P]): DecodeJson[JsonRpcBody[P]] =
DecodeJson(c => for {
jsonrpc <- (c --\ "jsonrpc").as[String]
method <- (c --\ "method").as[String]
params <- (c --\ "params").as[P]
id <- (c --\ "id").as[String]
} yield JsonRpcBody(jsonrpc, method, params, id))
implicit def sampleParamsDecodeJson: DecodeJson[SampleParams] =
DecodeJson(c => for {
_1 <- c.downN(0).as[String]
_2 <- c.downN(1).as[Int]
} yield SampleParams(_1, _2))
// これが欲しかったやつ
implicit def jsonRpcBodyWithSampleParams: DecodeJson[JsonRpcBody[SampleParams]] = jsonRpcBodyDecodeJson[SampleParams]
// implicit def jsonRpcBodyWithOtherParams: DecodeJson[JsonRpcBody[OtherParams]] = jsonRpcBodyDecodeJson[OtherParams]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment