将没有字符串的地图序列化为lift-json的键 [英] Serialize a map that doesn't have a string as a key with lift-json

查看:165
本文介绍了将没有字符串的地图序列化为lift-json的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎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 ?

推荐答案

定义您自己的序列化器[Map [A​​ny,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

就是这样。

这篇关于将没有字符串的地图序列化为lift-json的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆