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

自闭症网瘾萝莉.ら 提交于 2019-12-05 00:05:08

问题


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

What is the best way to bypass this limitation ?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/11387612/serialize-a-map-that-doesnt-have-a-string-as-a-key-with-lift-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!