I have two JsValue created from case class, i.e. Book and Book detail
val bookJson = Json.tojson(Book)
val bookDetailJson = Json.tojson(BookDetail)
and the format would be:
//Book
{
id: 1,
name: "A Brief History of Time"
}
//BookDetail
{
bookId: 1,
author: "Steven Hawking",
publicationDate: 1988,
pages: 256
}
How can I merge them to a single Json in play-framework 2.10? i.e.
//Book with detail
{
id: 1,
name: "A Brief History of Time",
bookId: 1,
author: "Steven Hawking",
publicationDate: 1988,
pages: 256
}
I was trying the transformation and failed to iterate through the second JsValue:
val mapDetail = (__).json.update(
__.read[JsObject].map { o =>
o.deepMerge( JsObject(Seq(("detail", bookDetailJson))) )
})
bookJson.validate(mapDetail).get
It would become one level down, which I don't really want.
//Book with detail
{
id: 1,
name: "A Brief History of Time",
detail: {
bookId: 1,
author: "Steven Hawking",
publicationDate: 1988,
pages: 256
}
}
Please let me know if any trick could provide on this Json transform. Many Thanks!
JsObject
class supports the++
method for combining twoJsObject
s. Have you tried casting them toJsObject
(if they already are not that type) and then using++
? – HoahoactzinJsObject
, you should be able to copy the fields from one into the other like so:val newObj = a.copy(fields = fields ++ b.fields)
. – Hoahoactzinjvalue.asInstanceOf[JObject]
wherejvalue
is theJValue
you want to convert – Hoahoactzin