将包含包含 mutableMap 的对象的大小写 class 转换为 json 并使用 lift 返回

Convert case class containing objects containing mutableMap to json and back using lift

我有一个案例 class 作为 :

case class Cart(cart_id :UUID, cart_entries :Map[String,CartEntry]){

  //override def toString: String = "Saini CartId = " + cart_id.toString

}

我正在使用 net.liftweb.json._ 将其转换为 json :

implicit val formats = Serialization.formats(NoTypeHints) + new UUIDserializer
val json = write(cart)
println(json)

Json 结果为

{"cart_id":"68eb787f-746c-4320-9ef4-8b5c7f0d7e21","cart_entries":[{"_1":"ABC","_2":{"sku_id":"ABC","quantity":12,"price":213.0}}]}

将我的 json 转换回购物车对象时 :

val jValue = read[Cart](json)

我遇到了这个异常。

[ERROR] [12/22/2016 17:11:23.784] [System-akka.actor.default-dispatcher-3] [akka://System/user/68eb787f-746c-4320-9ef4-8b5c7f0d7e21] No usable value for cart_entries No constructor for type interface scala.collection.mutable.Map, JArray(List(JObject(List(JField(_1,JString(ABC)), JField(_2,JObject(List(JField(sku_id,JString(ABC)), JField(quantity,JInt(12)), JField(price,JDouble(213.0))))))))) net.liftweb.json.MappingException: No usable value for cart_entries No constructor for type interface scala.collection.mutable.Map, JArray(List(JObject(List(JField(_1,JString(ABC)), JField(_2,JObject(List(JField(sku_id,JString(ABC)), JField(quantity,JInt(12)), JField(price,JDouble(213.0))))))))) at net.liftweb.json.Meta$.fail(Meta.scala:191) at net.liftweb.json.Extraction$.mkValue(Extraction.scala:357) at net.liftweb.json.Extraction$.net$liftweb$json$Extraction$$build(Extraction.scala:317) at net.liftweb.json.Extraction$$anonfun.apply(Extraction.scala:253) at net.liftweb.json.Extraction$$anonfun.apply(Extraction.scala:253) at scala.collection.immutable.List.map(List.scala:277) at net.liftweb.json.Extraction$.instantiate(Extraction.scala:253) at net.liftweb.json.Extraction$.newInstance(Extraction.scala:286) at net.liftweb.json.Extraction$.net$liftweb$json$Extraction$$build(Extraction.scala:315) at net.liftweb.json.Extraction$.net$liftweb$json$Extraction$$extract0(Extraction.scala:366) at net.liftweb.json.Extraction$.net$liftweb$json$Extraction$$extract0(Extraction.scala:199) at net.liftweb.json.Extraction$.extract(Extraction.scala:43) at net.liftweb.json.JsonAST$JValue.extract(JsonAST.scala:312) at net.liftweb.json.Serialization$.read(Serialization.scala:58) at What should i do ?

您的 cart_entries 字段定义为 scala.collection.mutable.Map。 Lift 的 JSON 序列化知道如何序列化 Map(可变或不可变),但它不知道如何反序列化为可变 Map。要修复它,请将您的地图定义为 scala.collection.immutable.Map 或将 TypeHints 添加到您的格式以支持可变类型。