为Json4s编写自定义序列化器

为Json4s编写自定义序列化器

问题描述:

由于Json4s仅在键是字符串时才带有Map序列化,所以我试图用Java枚举作为键为特定Map编写自定义序列化程序.

Since Json4s come with Map serialization only when the key is a String, I am trying to write my custom serializers for a specific Map with Java enums as key.

class HistoricalRecordCustomSerializer extends CustomSerializer[Map[QuotedData,Double]](
  format => (
    {
      case JArray(items) =>
        items.map{
                   case JObject(JField(name,JDouble(value))::Nil) => (QuotedData.valueOf(name),value)

                 }.toMap


    },
    {
      case x: Map[QuotedData,Double] =>
        JArray(
          x.map(entry =>
                  JObject(
                    List(
                      JField(entry._1.toString,JDouble(entry._2))
                    )
                  )
        ).toList
        )
} ) )

首先,此实现显然在序列化的情况下不起作用,因为已删除了x: Map[QuotedData,Double].此外,我无法使用它来获取json4s. 编写此自定义序列化程序的正确方法是什么?

First of all, this implementation clearly does not work in case of serializing, because x: Map[QuotedData,Double] is erased. Additionally, I can't manage to get json4s using it. What is the correct way to write this custom serializer?

Json4s在此阶段仅了解字符串键,因此您要实现的目标不适用于地图.

Json4s only knows about string keys at this stage, so what you're trying to achieve won't work with a map.