我使用spray-json
库来反序列化json
个对象。我希望能够从json字符串解析nscala-time库中指定的DateTime
对象。
我想反序列化这种形式的json字符串:
{"updatedAt": "2015-05-18T23:55:49.033Z"}
为此我使用spray-json
方法定义自己的协议。我的spray-json
协议如下:
import spray.json._
// I want to de-serialize an object from this library
import com.github.nscala_time.time.Imports._
object CustomProtocol extends DefaultJsonProtocol {
// There are other implicit objects that describe how to format other
// classes before the one below. All of them are independent from each other
implicit object DateTimeFormat extends RootJsonFormat[DateTime] {
def write(dateTime: DateTime) = JsString(dateTime.toString)
def read(json: JsValue) = {
json.asJsObject.getFields("updatedAt") match {
case Seq(JsString(timeStamp)) => DateTime.parse(timeStamp)
case other => deserializationError("DateTime expected, found \n" + other)
}
}
}
我的测试(使用scala-test)如下:
//Previous imports
import CustomProtocol._
test("Can parse DateTime from Json string") {
val DateTimeJson = """ {"updatedAt": "2015-05-18T23:55:49.033Z"} """
val DateTimefromJson = DateTimeJson.parseJson.convertTo[DateTime]
val realDateTime = DateTime.parse("2015-05-18T23:55:49.033Z")
assert(DateTimefromJson.equals(realDateTime))
我收到以下编译错误:
{Directory}/src/test/scala/messageJsonParserTest.scala:29: Cannot find
JsonReader or JsonFormat type class for com.github.nscala_time.time.Imports.DateTime
[error] val DateTimefromJson = DateTimeJson.parseJson.convertTo[DateTime]
有人能在我的代码中发现错误吗?
对不起,如果之前已经问过这个问题。在浏览了我的思想和互联网一整天之后,我一直无法找到解决方案。