案例类自动映射
总的来说,使用 JSON 的最简单方法是将案例类直接映射到 JSON(相同的字段名称,等效类型等)。
case class Person(
name: String,
age: Int,
hobbies: Seq[String],
pet: Pet
)
case class Pet(
name: String,
`type`: String
)
// these macros will define automatically the conversion to/from JSON
// based on the cases classes definition
implicit val petFormat = Json.format[Pet]
implicit val personFormat = Json.format[Person]
转换为 Json
val person = Person(
"Jsony McJsonface",
18,
Seq("Fishing", "Hunting", "Camping"),
Pet("Doggy", "dog")
)
Json.toJson(person).toString
// {"name":"Jsony McJsonface","age":18,"hobbies":["Fishing","Hunting","Camping"],"pet":{"name":"Doggy","type":"dog"}}
从 Json 转换
val str =
"""{
| "name" : "Jsony McJsonface",
| "age" : 18,
| "hobbies" : [ "Fishing", "Hunting", "Camping" ],
| "pet" : {
| "name" : "Doggy",
| "type" : "dog"
| }
|}""".stripMargin
Json.parse(str).as[Person]
// Person(Jsony McJsonface,18,List(Fishing, Hunting, Camping),Pet(Doggy,dog))