我去了这个json节点
...
"businessKeys": [
"product://color?product_code",
"product://?code"
]
...
经过一系列计算后,我有一个Json距离,但我不明白如何将那个对象转换为我的对象列表。因此,Json(istance)列出了[MyClass]。
MyClass(root: ParameterType, children: List[ParameterType] = List.empty)
ParameterType(parameter: String)
我有一个将String转换为MyClass等距的方法,因此我需要将Json解码为List [String],然后调用我的函数,或者有直接方法吗?谢谢
您需要实现自己的实现io.circe.Decoder
,可以将其从解码器转换为字符串。
请在下面找到一些示例代码:
import io.circe._
import io.circe.generic.auto._
object CirceExample {
class ParameterType(parameter: String) {
override def toString: String = parameter
}
class MyClass(root: ParameterType, children: List[ParameterType] = List.empty) {
override def toString: String = s"MyClass($root, $children)"
}
object MyClass {
/**
* Parsing logic from string goes here, for sake of example, it just returns empty result
*/
def parse(product: String): Either[String, MyClass] = {
Right(new MyClass(new ParameterType("example")))
}
// This is what need - just declare own decoder, so the rest of circe infrastructure can use it to parse json to your own class.
implicit val decoder: Decoder[MyClass] = Decoder[String].emap(parse)
}
case class BusinessKeys(businessKeys: List[MyClass])
def main(args: Array[String]): Unit = {
val json = "{ \"businessKeys\": [\n \"product://color?product_code\",\n \"product://?code\"\n ] }"
println(parser.parse(json).map(_.as[BusinessKeys]))
}
}
在我的情况下产生下一个输出:
Right(Right(BusinessKeys(List(MyClass(example, List()), MyClass(example, List())))))
希望这个能对您有所帮助!
嗨,找不到参数d的隐式值:io.circe.Decoder [package.BusinessKeys]
解决了circe.generic.auto的导入