将 Json 字符串转换为 Json 数组 Circe Scala?

Convert Json String to Json Array Circe Scala?

所以我在这里(请注意,这在语法上不正确,我只是想向您展示这个想法)

js = “a1,a2”

如何将 circe.JSON 字符串转换为 circe.JSON 数组?

    

expected js => [“a1”,”a2”]



目标是 return [“a1”,”a2”] 作为 Array[Byte]

的功能

因为,这不是很典型的情况,circe 不提供开箱即用的这种行为,所以你需要自己实现 EncoderDecoder。幸运的是,使用这个库很容易做到。

请参阅下面的代码示例:

import io.circe._
import io.circe.syntax._
import io.circe.generic.auto._

val separator = ","
// Implement own `Encoder` to render array of string as JSON string, separated with comma inside
implicit val encoder: Encoder[Array[String]] = Encoder[String].contramap(_.mkString(separator))

// Implement own `Decoder` to parse JSON string as array
implicit val decoder: Decoder[Array[String]] = Decoder[String].map(_.split(separator))

// Class added for sake of example, because I guess you will use string array as a part of another structure
case class Foo(a: Array[String]) {
  // override toString, because array toString works as default Object toString, which is not really readable
  // Made for example readability, you don't need to do in your code
  override def toString: String = s"Foo(a: ${a.mkString(", ")})"
}

val foo = Foo(Array("a1", "a2"))
val json = foo.asJson

println(json.noSpaces)
println(json.as[Foo])

产生下一个结果:

{"a":"a1,a2"}
Right(Foo(a: a1,a2))

希望对您有所帮助!