我想将array: String
转换为Seq[Message]
...
案例分类:
case class Message(name: String, sex: String)
来源:
[
{ "name": "Bean",
"sex": "F"
},
{
"name": "John",
"sex": "M"
}
]
目的地
Seq[Person]
如何转换?代码...
答案 0 :(得分:1)
您需要使用某种解码器/反序列器将字符串解码为case class
。 Scala中有大量的解码器。我最喜欢的circe之一是它的功能,并且也可以与scalajs一起很好地工作。
import io.circe._, io.circe.generic.auto._, io.circe.parser._, io.circe.syntax._
case class Message(name: String, sex: String)
val encoded =
"""
|[
| { "name": "Bean",
| "sex": "F"
| },
| {
| "name": "John",
| "sex": "M"
| }
|]
""".stripMargin
val decoded: Either[Error, List[Message]] = decode[List[Message]](encoded)
decoded match {
case Right(e) => println("success: " + e)
case Left(l) => println("failure: "+ l)
}
输出:
success: List(Message(Bean,F), Message(John,M))
如果您要寻找与Java兼容的简单格式,请查看https://github.com/FasterXML/jackson-module-scala