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

2

6

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

What is the best way to bypass this limitation ?

Advisement answered 8/7, 2012 at 23:40 Comment(3)
Aren't JSON objects limited to have only strings for keys?Hex
Yes, JSON objects are limited to have only strings for keys. They are, as a practical matter, the method names, so it's fitting.Matriculate
Yes, my question was how can you (de)serialize map that haven't string as key since there is this limitation.Advisement
F
5

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.

Feather answered 9/7, 2012 at 6:25 Comment(0)
D
0

In addition to the previous answer you can define instead:

def deserialize(implicit format: Formats): PartialFunction[(TypeInfo, JValue), Map[Any, Any]] = { Map() }

This doesn't break any other working map deserialization.

Ding answered 16/5, 2014 at 21:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.