Custom json serialization of structured scala case classes

 ̄綄美尐妖づ 提交于 2019-12-04 07:31:27

Argonaut does a great job. Mark Hibbard helped me out with getting the example below working. All that is needed is to create a codec for the types and it will implicitly add an asJson to your objects to turn them into strings. It will also add a decodeOption[YourClass] to strings to extract an object. The following:

package argonaut.example

import argonaut._, Argonaut._

abstract class Message
case class CardDrawn(player: Long, card: Int, mType: String = "CardDrawn") extends Message
case class CardSet(cards: List[CardDrawn], mType: String = "CardSet") extends Message

object CardSetExample  {

  implicit lazy val CodecCardSet: CodecJson[CardSet] = casecodec2(CardSet.apply, CardSet.unapply)("cards","mType")
  implicit lazy val CodecCardDrawn: CodecJson[CardDrawn] = casecodec3(CardDrawn.apply, CardDrawn.unapply)("player", "card", "mType")

  def main(args: Array[String]): Unit = {
    val value = CardSet(List(CardDrawn(1L,2),CardDrawn(3L,4)))
    println(s"Got some good json ${value.asJson}")

    val jstring =
      """{
        | "cards":[
        |   {"player":"1","card":2,"mType":"CardDrawn"},
        |   {"player":"3","card":4,"mType":"CardDrawn"}
        | ],
        | "mType":"CardSet"
        | }""".stripMargin

    val parsed: Option[CardSet] =
      jstring.decodeOption[CardSet]

    println(s"Got a good object ${parsed.get}")
  }
}

outputs:

Got some good json {"cards":[{"player":"1","card":2,"mType":"CardDrawn"},{"player":"3","card":4,"mType":"CardDrawn"}],"mType":"CardSet"}

Got a good object CardSet(List(CardDrawn(1,2,CardDrawn), CardDrawn(3,4,CardDrawn)),CardSet)

The question is old but maybe someone could still find it helpful. Apart from Argonaut, Scala has several Json libraries. Here you can find a list of them updated to the beginning of 2016 (and it still gives you a good overall picture). Most of them (probably all) should allow you to come up with a drier version of your custom serializer/deserailizer. My preference goes to json4s which aims to provide a single AST across multiple libraries including Jackson (a bit like slf4j does for logging libraries). In this post you can find a working example of a Json custom serializer/deserializer using Json4s and Akka Http.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!