Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing JSON Date Time in Scala/Play

I have the following Read defined:

import org.joda.time.DateTime;

implicit val userInfoRead: Reads[UserInfo] = (
  (JsPath \ "userName").readNullable[String] and
] (JsPath \ "startDate").readNullable[DateTime]
 (UserInfo.apply _)

With the following JSON object being passed in:

  "userInfo" : {
    "userName": "joeuser",
    "startDate": "2006-02-28"
  }

When I validate this data I get the following error:

(/startDate,List(ValidationError(validate.error.expected.jodadate.format,WrappedArray(yyyy-MM-dd))))))

Any suggestions on what I'm missing in the formatting?

like image 897
ccudmore Avatar asked Oct 15 '14 15:10

ccudmore


1 Answers

As far as I can see, the issue is probably just the format not matching what Joda is expecting. I simplified a bit, and this worked for me:

scala> import org.joda.time.DateTime
import org.joda.time.DateTime

scala> case class UserInfo(userName: String, startDate: DateTime)
defined class UserInfo

scala> implicit val dateReads = Reads.jodaDateReads("yyyy-MM-dd")
dateReads: play.api.libs.json.Reads[org.joda.time.DateTime] = play.api.libs.json.DefaultReads$$anon$10@22db02cb

scala> implicit val userInfoReads = Json.reads[UserInfo]
userInfoReads: play.api.libs.json.Reads[UserInfo] = play.api.libs.json.Reads$$anon$8@52bcbd5d

scala> val json = Json.parse("""{
     |     "userName": "joeuser",
     |     "startDate": "2006-02-28"
     |   }""")
json: play.api.libs.json.JsValue = {"userName":"joeuser","startDate":"2006-02-28"}

scala> json.validate[UserInfo]
res12: play.api.libs.json.JsResult[UserInfo] = JsSuccess(UserInfo(joeuser,2006-02-28T00:00:00.000-05:00),)
like image 115
acjay Avatar answered Sep 20 '22 11:09

acjay