使用Json4s和自定义序列化程序多态读取JSON

时间:2014-01-21 19:39:02

标签: json scala serialization json4s

我有以下课程hierachy:

object Calendar {
  trait DayType
  case object Weekday extends DayType
  case object Weekend extends DayType
  case object Holiday extends DayType
}

trait Calendar {
  def dateType(date: LocalDate): Calendar.DayType
}

class ConstantCalendar(dayType: Calendar.DayType) extends Calendar {
  override def dateType(date: LocalDate) = dayType
}

case object DefaultCalendar extends ConstantCalendar(Calendar.Weekday)

case class WeekdaysCalendar(defaults: Array[Calendar.DayType]) extends Calendar {
  override def dateType(date: LocalDate) = defaults(date.getDayOfWeek - 1)
}

case class CustomCalendar(defaultCalendar: Calendar = DefaultCalendar,
                     dates: Map[LocalDate, Calendar.DayType] = Map.empty)
    extends Calendar {
  private def defaultType(date: LocalDate) = defaultCalendar.dateType(date)
  private val dateMap = dates.withDefault(defaultType)

  override def dateType(date: LocalDate) = dateMap(date)
}

我定义了以下序列化程序:

class JsonFormats(domainTypeHints: TypeHints,
                  domainCustomSerializers: List[Serializer[_]] = Nil,
                  domainFieldSerializers: List[(Class[_], FieldSerializer[_])] = Nil)
    extends DefaultFormats {
  override val typeHintFieldName = "type"
  override val typeHints         = domainTypeHints
  override val customSerializers = JodaTimeSerializers.all ++ domainCustomSerializers
  override val fieldSerializers  = domainFieldSerializers
}

class JsonCalendarSerializer extends CustomSerializer[CustomCalendar]( format => (
    {
      case JObject(JField("type", JString("CustomCalendar")) ::
                   JField("defaultCalendar", JString(defaultCalendar)) ::
                   JField("dates", dates) ::
                   Nil
                  ) =>
        CustomCalendar(defaultCalendar) // TODO dates
    },
    {
      case cal: CustomCalendar =>
        val dates = cal.dates.foldLeft(JObject()) { (memo, dt) =>
          dt match {
            case (d, t) => memo ~ (f"${d.getYear}%04d-${d.getMonthOfYear}%02d-${d.getDayOfMonth}%02d", t.toString)
          }
                                                  }
        ("type" -> "CustomCalendar") ~
        ("defaultCalendar" -> cal.defaultCalendar) ~
        ("dates" -> dates)
    }
    ))

implicit val jsonFormats = new JsonFormats(ShortTypeHints(List(Calendar.Weekday.getClass,
                                                               Calendar.Weekend.getClass,
                                                               Calendar.Holiday.getClass,
                                                               classOf[CustomCalendar])),
                                           new JsonCalendarSerializer :: Nil)

我必须创建一个自定义的Serializer来解决这个问题,在Json4s中,Map键必须是字符串。

我有一个文件可能包含某些日历的数据,但我事先并不知道它是哪种日历类型。

当我尝试以下操作时:

val cal = CustomCalendar("default", Map(new LocalDate(2013, 1, 1) -> Calendar.Holiday))
val ser = Serialization.write(cal)
val cal2: Calendar = Serialization.read(ser)

我明白了:

org.json4s.package$MappingException: Do not know how to deserialize 'CustomCalendar'
    at org.json4s.Extraction$ClassInstanceBuilder.org$json4s$Extraction$ClassInstanceBuilder$$mkWithTypeHint(Extraction.scala:444)
    at org.json4s.Extraction$ClassInstanceBuilder$$anonfun$result$6.apply(Extraction.scala:452)
    at org.json4s.Extraction$ClassInstanceBuilder$$anonfun$result$6.apply(Extraction.scala:450)
    at org.json4s.Extraction$.org$json4s$Extraction$$customOrElse(Extraction.scala:462)
    at org.json4s.Extraction$ClassInstanceBuilder.result(Extraction.scala:450)
    at org.json4s.Extraction$.extract(Extraction.scala:306)
    at org.json4s.Extraction$.extract(Extraction.scala:42)
    at org.json4s.ExtractableJsonAstNode.extract(ExtractableJsonAstNode.scala:21)
    at org.json4s.jackson.Serialization$.read(Serialization.scala:50)

所以似乎Json4s无法找到我的序列化器。

所以...任何提示?关于如何让Json4s使用非String键序列化/反序列化Maps,或者如何使其工作?

谢谢!

1 个答案:

答案 0 :(得分:2)

最后,我按如下方式实现了JsonCalendarSerializer:

class JsonCalendarSerializer extends CustomSerializer[CustomCalendar]( format => (
    {
      case JObject(JField("defaults", JString(defaults)) ::
                   JField("dates", JObject(dateList)) ::
                   Nil
                  ) =>
        val dates = dateList map {
          case JField(dt, JString(t)) =>
            val tp = t match {
              case "Weekday" => Calendar.Weekday
              case "Weekend" => Calendar.Weekend
              case "Holiday" => Calendar.Holiday
            }

            (LocalDate.parse(dt), tp)
        }

        CustomCalendar(defaults, dates.toMap)
    },
    {
      case cal: CustomCalendar =>
        val dates = cal.dates.foldLeft(JObject()) { (memo, dt) =>
          dt match {
            case (d, t) => memo ~ (d.toString, t.toString)
          }
                                                  }
        (format.typeHintFieldName -> classOf[CustomCalendar].getSimpleName) ~
        ("defaults" -> cal.defaultCalendar) ~
        ("dates" -> dates)
    }
    ))

我从反序列化程序中删除了JField("type"...)并修复了序列化程序,以便调用format.typeHintFieldNameclassOf[CustomCalendar].getSimpleName,这似乎可以解决问题。