如何使用 Circe 从 Doobie Scala PostgreSQL 数据库中读取 JSON? [英] How to read JSON out of Doobie Scala PostgreSQL Database with Circe?

查看:76
本文介绍了如何使用 Circe 从 Doobie Scala PostgreSQL 数据库中读取 JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试创建以下隐式,以便我可以从 postgreSQL 数据库获取/读取数据.我已经尝试添加推荐的隐式,但它们变成灰色并且似乎未使用.

I've tried creating the below implicit so that I can GET/read data from the postgreSQL database. I've tried add in the recommended implicits but they turn grey and seem to be unused.

implicit val get: Get[JobPostDetails] =
 Get[Json].temap(_.as[JobPostDetails].leftMap(_.show))

  def createTable: doobie.Update0 = {
    sql"""
         |CREATE TABLE IF NOT EXISTS jobs (
         |  id TEXT PRIMARY KEY,
         |  details JSON NOT NULL
         |)
       """.stripMargin
      .update
  }

case class JobPost(id: String, details: JobPostDetails)

case class JobPostDetails(title: String, description: String, salary: Double, employmentType: String, employer: String)

[warn] insecure HTTP request is deprecated 'http://repo.typesafe.com/typesafe/releases/'; switch to HTTPS or opt-in as ("Typesafe repository" at "http://repo.typesafe.com/typesafe/releases/").withAllowInsecureProtocol(true)
[info] Compiling 1 Scala source to /Users/ryanmcavoy/fullStackRyan/job-board/target/scala-2.13/classes ...
[error] /Users/ryanmcavoy/fullStackRyan/job-board/src/main/scala/io/github/jobboard/model/JobPost.scala:31:44: value leftMap is not a member of io.circe.Decoder.Result[io.github.jobboard.model.JobPostDetails]
[error]       Get[Json].temap(_.as[JobPostDetails].leftMap(_.show))
[error]                                            ^
[error] one error found
[error] (Compile / compileIncremental) Compilation failed
[error] Total time: 1 s, completed 3 Sep 2020, 16:41:02
sbt:job-board> 


[![enter image description here][1]][1]

[![enter image description here][2]][2]


  [1]: https://i.stack.imgur.com/PvKHJ.png
  [2]: https://i.stack.imgur.com/9QPz6.png

推荐答案

旧版本的 Scala 提供了 .leftMapEither(因为这是 Circe Result 的别名),这可能在您使用的来源中提到过.

Older versions of Scala provided .leftMap to Either (because this is what Circe Result aliases to), which might have been mentioned in the source that you used.

然而,较新的版本稍微清理了 API,他们使用 .left.right 来聚合许多方法.所以 .leftMap 变成了 .left.map,但你也有 .left.flatMap 等,这样你就可以使用 Either 不仅在符合右偏"的用例中很容易.

However, newer versions cleaned up API a bit to they used .left and .right to aggregate many of the methods. So .leftMap became .left.map, but you have also .left.flatMap etc, so that you can use Either easily not only in use cases that align with Either being Right-biased.

长话短说 - 在较新版本的 Scala 中将 .leftMap 替换为 .left.map.

So long story short - replace .leftMap with .left.map in newer versions of Scala.

这篇关于如何使用 Circe 从 Doobie Scala PostgreSQL 数据库中读取 JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆