4

我收到此错误:

Cannot decode into a value of type com.blah.rest.model.UserProfile, 
because no EntityDecoder[cats.effect.IO, com.blah.rest.model.UserProfile] 
instance could be found.

对于以下案例类:

case class UserProfile(id: Option[Int], firstName: String, lastName: String)

遇到POST代码错误:

case req @ POST -> Root / "v1" / "profiles" =>
  req.as[UserProfile] flatMap {(up: UserProfile) =>
    Ok(service.createProfile(up).asJson)
  }

具有以下POST主体:

{
   "firstName": "Jack",
   "lastName": "Appleseed"
}

我认为当身体被转换为时会发生这种UserProfile情况req.as[UserProfile]

但是,这是一个普通的案例类,EntityDecoder应该是自动派生的!我知道akka-http会!

有什么想法/建议吗?

请注意: Http4sVersion = "0.18.0-M4"circe version "0.9.0-M1"

4

2 回答 2

2

答案是:

req.decodeJson[UserProfile] flatMap {(up: UserProfile) =>
    Ok(service.createProfile(up).asJson)
  }

你得到的原因是从 Circe 解码器到 http4s EntityDecoder 的桥梁并不是隐含的。如果您是纯粹的 JSON API,您可以制作一个,但这不是库通常可以做出的假设。

于 2017-10-31T00:27:24.007 回答
1

添加此依赖项: "io.circe" %% "circe-generic" % "0.9.1"

为我解决了将案例类自动编码为 JSON 的问题。

它允许所需的导入:import io.circe.generic.auto._

于 2018-02-14T14:33:32.780 回答