Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize a map that doesn't have a string as a key with lift-json

It seems like lift-json is limited to maps that have Strings as keys.

What is the best way to bypass this limitation ?

like image 376
Atol Avatar asked Jul 08 '12 23:07

Atol


1 Answers

Define your own Serializer[Map[Any, Any]].

import net.liftweb.json._
import ext._

object MapSerializer extends Serializer[Map[Any, Any]] {
  def serialize(implicit format: Formats): PartialFunction[Any, JValue] = {
    case m: Map[_, _] => JObject(m.map({
      case (k, v) => JField(
        k match {
          case ks: String => ks
          case ks: Symbol => ks.name
          case ks: Any => ks.toString
        },
        Extraction.decompose(v)
      )
    }).toList)
  }

  def deserialize(implicit format: Formats): PartialFunction[(TypeInfo, JValue), Map[Any, Any]] = {
    sys.error("Not interested.")
  }
}

Then add it to the implicit Formats variable.

implicit val formats = DefaultFormats + MapSerializer

That's all.

like image 195
missingfaktor Avatar answered Sep 26 '22 05:09

missingfaktor