1

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
        )
} ) )

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?

flavian
  • 28,161
  • 11
  • 65
  • 105
Edmondo
  • 19,559
  • 13
  • 62
  • 115

2 Answers2

1

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

Casual Jim
  • 1,179
  • 7
  • 13
1

You can use a custom key serializer

For instance

    class UUIDKeyJSonSerializer extends CustomKeySerializer[UUID](format => ( {
  case s: String => {
    UUID.fromString(s)
  }
}, {
  case x: UUID => {
    x.toString
  }
}
  ))

You need to map your object to a String and viceversa

David
  • 31
  • 6