I have JSON structure:
{
"date": "2015-01-01",
"id": 100,
"movies":[
{
"id": 1,
"length": 131,
"timestamp": 1447837200
},
{
"id": 2,
"length": 131,
"timestamp": 1447840800
}
]
}
I need some validation: - "date" is a valid date; - "id" - is a Number in present List; - "movies" - is a List of Objects;
And transformation: - "timestamp" - Parse unixtimestamp to Date string ( HH:mm )
I need put "date" and "id" from root to each array element
So, result object:
[
{
"id": 1,
"length": 131,
"timestamp": "09:00",
"parent_id": 100,
"date": "2015-01-01"
},
{
"id": 2,
"length": 131,
"timestamp": "10:00",
"parent_id": 100,
"date": "2015-01-01"
}
]
I wrote some code, witch transform timestamp, but it looks terrible..
val inputJson = play.api.libs.json.Json.parse(
"""{
"date": "2015-01-01",
"id": 100,
"movies":[
{
"id": 1,
"length": 131,
"timestamp": 1447837200
},
{
"id": 2,
"length": 131,
"timestamp": 1447840800
}
]
}"""
)
val timestampTransform = (
( __ \ "timestamp").json.update(
__.read[JsNumber].map(
timestamp => {
JsString(new DateTime(timestamp.asOpt[Int].getOrElse(0)).toString("HH:mm"))
} )
))
val reads = ( __ \ 'movies).json.update(
__.read[JsArray].map(
movies => {
val result = movies.as[List[JsObject]].map(
element => {
element.transform(timestampTransform).get
})
Json.toJson(result)
}
)
)
println(inputJson.transform(reads))