Overall the easiest way to work with JSON is to have a case class mapping directly to the JSON (same fields name, equivalent types, etc.).
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]
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"}}
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))