简体   繁体   中英

spray.json.DeserializationException: Expected String as JsString, but got {}

I am using Either implementation for my object because I am expecting an empty Json for one of the parameter in the object. Here is the object:

case class Record(id: String, version: Long, payload: Either[PayloadObject, String]))

I am trying to unit test this sending an empty json string which is like this:

val jsonString = """
     | {
     |   "id":"someId"
     |   "version":123456
     |   "payload":{}
     | }
|""".stripMargin

This is my unit test where I am deserializing the above json String:

{
val deserialized = Record("someId", 123456L, Right(""))
val result = jsonString.convertTo[Record]
result must equal(deserialized)
}

This is throwing error. spray.json.DeserializationException: Expected String as JsString, but got {}. How to represent the variable serialized as an empty JsString to run the unit tests? Thanks

If I understand your question correctly, you need to define a custom format for your case class.

case class Record(id: String, version: Long, payload: Either[JsObject, String])

object Record {

  implicit val recordFormat: RootJsonReader[Record] = (json: JsValue) =>
    json.asJsObject.getFields("id", "version", "payload") match {
      case Seq(JsString(id), JsNumber(version), JsObject.empty)    => Record(id, version.toLong, Right(""))
      case Seq(JsString(id), JsNumber(version), payload: JsObject) => Record(id, version.toLong, Left(payload))
      case _                                                       => throw new Exception("Invalid record")
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM