如何使用Json4s从Json中提取我的case类?

时间:2018-04-17 13:34:29

标签: json scala unmarshalling case-class json4s

在akka scala应用程序中,我使用了休息端点。因此,我想将其响应映射到案例类,但我还想通过转换某些属性来简化这些案例类的处理,例如:那些包含日期的。

所以给了Json:

{
    "id": "20180213165959sCdJr",
    "createdAt": "2018-02-13T16:59:59.570+0000",
    "finishedAt": "2018-02-13T17:00:18.118+0000"
}

我想用它创建这样一个clase类:

case class FinishedRun
(
  id: String,
  createdAt: Date,
  finishedAt: Date
)

我创建了这个construtor:

object FinishedRun {

  def apply(id: String,
            createdAt: String,
            finishedAt: String
           ): FinishedRun = {

    val getDate = (jsonValue: String) => {
      val format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
      format.parse(jsonValue)
    }


    new FinishedRun(id, createdAt = getDate(createdAt), finishedAt = getDate(finishedAt))
  }
}

虽然这适用于从头开始初始化一个case类,但我在json4s libary的帮助下通过parse(json).as[FinishedRun]方法无法提取这个case类。

看来json4s没有调用case类的构造函数,因此无法提取它,抛出:

No usable value for createdAt
Invalid date '2018-02-13T16:59:59.570+0000'
org.json4s.package$MappingException: No usable value for createdAt
Invalid date '2018-02-13T16:59:59.570+0000'
    at org.json4s.reflect.package$.fail(package.scala:95)

Json4s正确解析日期我错过了什么?

这是我的测试用例:

import org.json4s._
import org.json4s.native.JsonMethods._
import org.scalatest.FlatSpec


class MarshallingTest extends FlatSpec {
  implicit val formats = DefaultFormats

  it should "marshall json object with date iso strings into a case class with Date properties" in {
    val json =
      """
        |{
        |    "id": "20180213165959sCdJr",
        |    "createdAt": "2018-02-13T16:59:59.570+0000",
        |    "finishedAt": "2018-02-13T17:00:18.118+0000"
        |}
      """.stripMargin

    val expected = FinishedRun(
      id = "20180213165959sCdJr",
      createdAt = "2018-02-13T16:59:59.570+0000",
      finishedAt = "2018-02-13T17:00:18.118+0000"
    )
    val actual = parse(json).extract[FinishedRun]

    assert(actual == expected)
  }
}

2 个答案:

答案 0 :(得分:1)

您需要定义CustomSerializer(1)CustomSerializer(2)。我将日期类型从Date更改为ZonedDateTime

import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter

import org.json4s._
import org.json4s.JsonAST._
import org.json4s.JsonDSL._
import org.json4s.native.JsonMethods._
import org.scalatest.FlatSpec

case class FinishedRun
(
  id: String,
  createdAt: ZonedDateTime,
  finishedAt: ZonedDateTime
)

object FinishedRunSerializer {
  val dateTimeFmt = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
}

class FinishedRunSerializer extends CustomSerializer[FinishedRun](
  format => ( {
    case jObj: JObject =>
      implicit val fmt = format
      val id = (jObj \ "id").extract[String]
      val created = ZonedDateTime.parse((jObj \ "createdAt").extract[String],
        FinishedRunSerializer.dateTimeFmt)
      val finished = ZonedDateTime.parse((jObj \ "finishedAt").extract[String],
        FinishedRunSerializer.dateTimeFmt)
      FinishedRun(id, created, finished)
  }, {
    case finishedRun: FinishedRun =>
      ("id" -> finishedRun.id) ~
        ("createdAt" -> finishedRun.createdAt.format(FinishedRunSerializer.dateTimeFmt)) ~
        ("finishedAt" -> finishedRun.finishedAt.format(FinishedRunSerializer.dateTimeFmt))
  }
  ))

在您的测试或使用它的地方,请不要忘记带FinishedRunSerializer

implicit val formats = DefaultFormats + new FinishedRunSerializer()

答案 1 :(得分:0)

一个简单的解决方案是在 org.json4s 中使用 Serialization 特性。您应该能够执行以下操作:

val finishedRun = read[FinishedRun](json)

有关详细信息和示例,请参阅此链接:https://github.com/json4s/json4s#serializing-polymorphic-lists