gpt4 book ai didi

scala - 将 Json4S 迁移到 Circe

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

我有以下用 json4s 编写的代码,可以编译并正常工作

import org.json4s._
def jsonRead[T <: AnyRef](input: String)(implicit m: Manifest[T]): T = {
Try(read[T](input)).get
}

def jsonWrite[T <: AnyRef](input: T)(implicit m: Manifest[T]): String = {
write[T](input).toString
}

我写了下面的Circe代码

import io.circe._
import io.circe.syntax._
import io.circe.generic.auto._
import io.circe.parser.decode
def unmarshall[T <: AnyRef](input: String)(implicit m: Manifest[T]) : T ={
decode[T](input).right.get
}
def marshall[T <: AnyRef](input: T)(implicit m: Manifest[T]) : String = {
input.asJson.toString
}

但是我得到了错误

Error:(27, 16) could not find implicit value for parameter decoder: io.circe.Decoder[T] decode[T](json).right.get
Error:(27, 16) not enough arguments for method decode: (implicit decoder: io.circe.Decoder[T])Either[io.circe.Error,T]. Unspecified value parameter decoder. decode[T](json).right.get
Error:(30, 11) could not find implicit value for parameter encoder: io.circe.Encoder[T] obj.asJson.toString
Error:(30, 11) not enough arguments for method asJson: (implicit encoder: io.circe.Encoder[T])io.circe.Json. Unspecified value parameter encoder. obj.asJson.toString

最佳答案

json4scirce 是不同的库,它们以不同的方式工作,这就是为什么你不能使用相同的技术。 json4s read 需要一个 Manifest 来从 Json 中提取值,而 circe 需要一个类型类 Decoder 的实例。如果你想在你的例子中使用 circe 你应该写这样的东西

def unmarshall[T <: AnyRef](input: String)(implicit d: Decoder[T]) : T = {
decode[T](input).right.get
}
def marshall[T <: AnyRef](input: T)(implicit e: Encoder[T]) : String = {
input.asJson.toString
}

要理解我建议阅读这两个实现的差异,它们对于理解这两个库如何做它们的工作非常有用。您可以在 json4s native read 的签名中看到差异和圈子decode .我将在此处复制签名的重要部分,以解释这两个库之间的根本区别。 json4s原生的签名read

def read[A](input: String)(implicit mf: Manifest[A]): A

这可以解释为“如果你为它提供 Scala Manifest,我可以将 String 转换为任何类型 A”。因为Manifest是用于反射的 Scala 特性,您可以推断 read 将使用反射。

圈子的签名decode是不同的:

def decode[A](input: String)(implicit d: Decoder[A]): Either[Error, A]

可以理解为“如果你为它提供一个 circe Decode 实例,我可以尝试将一个 String 转换成一个类型 A”。 Decoder typeclass 只是告诉系统如何从 json 中解码 A 类型的值。

关于scala - 将 Json4S 迁移到 Circe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41296319/

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