你如何编写一个json4s CustomSerializer来处理集合

时间:2015-11-09 17:34:16

标签: scala functional-programming deserialization json4s

我有一个类,我试图使用json4s CustomSerializer功能反序列化。由于inability of json4s to deserialize mutable collections,我需要这样做。

这是我想要反序列化的类的基本结构(不要担心为什么类的结构是这样的):

case class FeatureValue(timestamp:Double)

object FeatureValue{
  implicit def ordering[F <: FeatureValue] = new Ordering[F] {
    override def compare(a: F, b: F): Int = {
      a.timestamp.compareTo(b.timestamp)
    }
  }
}

class Point {
  val features = new HashMap[String, SortedSet[FeatureValue]]

  def add(name:String, value:FeatureValue):Unit = {
    val oldValue:SortedSet[FeatureValue] = features.getOrElseUpdate(name, SortedSet[FeatureValue]())
    oldValue += value
  }
}

Json4s将此序列化得很好。序列化实例可能如下所示:

{"features":
  {
   "CODE0":[{"timestamp":4.8828914447482E8}],
   "CODE1":[{"timestamp":4.8828914541333E8}],
   "CODE2":[{"timestamp":4.8828915127325E8},{"timestamp":4.8828910097466E8}]
  }
}

我尝试过编写自定义反序列化程序,但我不知道如何处理列表尾部。在普通的匹配器中,您可以递归地调用自己的函数,但在这种情况下,函数是匿名的,并通过json4s API调用。我找不到任何处理这个问题的例子,我无法弄明白。

目前,我只能在其值中匹配单个哈希键和单个FeatureValue实例。以下是CustomSerializer:

import org.json4s.{FieldSerializer, DefaultFormats, Extraction, CustomSerializer}
import org.json4s.JsonAST._

class PointSerializer extends CustomSerializer[Point](format => (
  {
    case JObject(JField("features", JObject(Nil)) :: Nil) => new Point
    case JObject(List(("features", JObject(List(
      (feature:String, JArray(List(JObject(List(("timestamp",JDouble(ts)))))))))
    ))) => {
      val point = new Point
      point.add(feature, FeatureValue(ts))
      point
    }
  },
  {
    // don't need to customize this, it works fine
    case x: Point => Extraction.decompose(x)(DefaultFormats + FieldSerializer[Point]())
  }
  ))

如果我尝试更改为使用:: separate list格式,到目前为止我遇到了编译器错误。即使我没有遇到编译器错误,我也不确定我会用它们做什么。

1 个答案:

答案 0 :(得分:4)

您可以在模式匹配中获取json功能列表,然后映射此列表以获取Feature及其代码。

class PointSerializer extends CustomSerializer[Point](format => (
  {
    case JObject(List(("features", JObject(featuresJson)))) => 
      val features = featuresJson.flatMap { 
        case (code:String, JArray(timestamps)) =>
          timestamps.map { case JObject(List(("timestamp",JDouble(ts)))) =>
            code -> FeatureValue(ts)
          }
      }

      val point = new Point
      features.foreach((point.add _).tupled)
      point
  }, {
    case x: Point => Extraction.decompose(x)(DefaultFormats + FieldSerializer[Point]())
  }
))

将您的json反序列化如下:

import org.json4s.native.Serialization.{read, write}
implicit val formats = Serialization.formats(NoTypeHints) + new PointSerializer

val json = """
{"features":
  {
   "CODE0":[{"timestamp":4.8828914447482E8}],
   "CODE1":[{"timestamp":4.8828914541333E8}],
   "CODE2":[{"timestamp":4.8828915127325E8},{"timestamp":4.8828910097466E8}]
  }
}
"""

val point0 = read[Point]("""{"features": {}}""")
val point1 = read[Point](json)

point0.features // Map()
point1.features 
// Map(
//   CODE0 -> TreeSet(FeatureValue(4.8828914447482E8)), 
//   CODE2 -> TreeSet(FeatureValue(4.8828910097466E8), FeatureValue(4.8828915127325E8)), 
//   CODE1 -> TreeSet(FeatureValue(4.8828914541333E8))
// )