我想为JSON序列化定义一个类类,如下所示:
case class Foo(id: String, variety: Variety)
sealed trait Variety
case object Bar extends Variety { override def toString = "1" }
case object Baz extends Variety { override def toString = "2" }
它应该像这样序列化和反序列化:
write[Foo](Foo("foo1", Bar))
"""{"id":"foo1", "variety":"1"}"""
read[Foo]("""{"id":"foo2", "variety":"2"}""")
Foo("foo2", Baz)
但它序列化为 {"id":"foo2", "variety":{}}
并且无法反序列化。是否可以使用这样的案例对象?我正在使用升降机-json_2.10 2.6-M2?
有没有更好的方法来处理使用 lift-json 的枚举?
而不是案例对象,将Variety
作为案例类并Bar
/Baz
val
s
我使用以下类为案例对象创建自定义序列化程序。只需选择 fieldKey 和 identifierOverride 以适合您的情况,如果您担心 json 的格式。
object SpecialObjectSerializers {
val FieldKeyDefault = "scalaObject"
class SingleObjectSerializer[T <: AnyRef](obj: T, FieldKey : String = FieldKeyDefault,
identifierOverride : Option[JValue] = None) extends Serializer[T] {
val Identifier = identifierOverride.getOrElse(JString(obj.getClass.getName))
override def serialize(implicit format: Formats): PartialFunction[Any, JValue] = {
case `obj` =>
JObject(List(JField(FieldKey, Identifier)))
}
override def deserialize(implicit format: Formats): PartialFunction[(TypeInfo, JValue), T] = {
case (_, JObject(List(JField(FieldKey, Identifier)))) => obj
}
}
class RichSerializer[T](serializer: Serializer[T]) {
def +(that: Serializer[T]) = {
new Serializer[T] {
override def deserialize(implicit format: Formats) = serializer.deserialize.orElse(that.deserialize)
override def serialize(implicit format: Formats) = serializer.serialize.orElse(that.serialize)
}
}
}
implicit def toRichSerializer[T](serializer: Serializer[T]) = new RichSerializer(serializer)
def caseObjectsSerializer[T <: AnyRef](objs: T*): Serializer[T] = {
val serializers: Seq[Serializer[T]] = objs.map(new SingleObjectSerializer(_))
serializers.reduceLeft[Serializer[T]] {
case (s1, s2) => s1 + s2
}
}
}