If I have an incoming JSON of following structure
[
{
"personId" : 12,
"name": "John Doe",
"age": 48,
"birthdate": "12/1/1954",
"relationships": [
{
"relationType":"parentOf",
"value" : "Johnny walker"
},
{
"relationType":"sonOf",
"value" : "Charles Smith"
}
]
},
{
"personId" : 13,
"name": "Merry Christmas",
"age": 28,
"birthdate": "12/1/1985",
"relationships": [
{
"relationType":"sisteOf",
"value" : "Will Smith"
},
{
"relationType":"cousinOf",
"value" : "Brad Pitt"
}
]
}
]
And requirement is that for each Person record controller will have to carve out relationships array and store each record from it in a separate relationship table with personId association while persisting this incoming JSON.
And subsequently when querying these persons records system will have to lookup relationships for each person from relationships table and inject them to form the same above looking JSON to give back to UI for rendering.
What's the best efficient way to perform this "carve out" and later "inject" operations using Play framework in Scala? (using Slick in persistent layer APIs) I have looked at this JSON transformation link and json.pickBranch in there but not quite sure if that'll be fully applicable here for "carve out" and "inject" use cases for preparing JSON shown in the example. are there any elegant ideas?
One way, which is pretty straightforward, is to use
caseclasses along with PlayJsoninceptionsNow you can convert a json value to
Personby using the following code, provided thatjsValueis a json value of typeJsValue(which in play controllers you can get byrequest.body.asJson):In Play controllers, you can
For converting a
Personto json you can use the following code provided thatpersonis a value of typePersonin your context:The only remaining thing is your Slick schemas which is pretty straight forward.
One option is to use a simple schema for
Person, without relations and one schema forRelationwith a foreign key toPersontable. Then you need to find all relations associated with a specificPerson, namelypersonand then append them to thatpersonby calling thewithRelationshipsmethod which gives you a newPersonwhich you can serve as json: