使用带有lift-json的Map [String,Any]属性反序列化案例类 [英] Deserializing case classes with Map[String,Any] properties with lift-json

查看:181
本文介绍了使用带有lift-json的Map [String,Any]属性反序列化案例类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

几天来,我一直在努力通过lift-json实现一些简单的事情:将映射序列化为JSON.

I've been struggling with something that should be simple through lift-json for days: serializing a map to JSON.

我知道,我知道–根对象还不能成为List或Map" –但是我现在愿意包装一个case类,但是我仍然无法使它起作用.多亏了一些堆栈溢出的帮助,我才能进行序列化工作,但是无法从字符串中反序列化.我收到类似没有可用的 _ 值"和没有有关类型的信息"之类的错误.

I know, I know – "Root object can't yet be List or Map" – but I'm willing to wrap in a case class for now, and I still haven't been able to get this to work. Thanks to some stack overflow help, I've got serialization working, but I can't deserialize it from a string. I get errors like "No usable value for _" and "No information known about type."

网络上还有其他较旧的文章指出了类型提示是答案,但这只会导致另一个错误,例如不知道如何对 _ _进行反序列化".

There are other, older posts on the web that indicate type hints are the answer, but that just leads to a different error like "Do not know how to deserialize __."

对于Scala 2.8.0和Lift 2.2:

For Scala 2.8.0 and Lift 2.2:

import net.liftweb.json._
import net.liftweb.json.Serialization.{read, write}

case class MapWrap(data: Map[String, Any])

object Scaffold {
    def main(args: Array[String]) {

        implicit val formats = Serialization.formats(NoTypeHints)
        //implicit val formats = Serialization.formats(ShortTypeHints(List(classOf[MapWrap])))
        //implicit val formats = Serialization.formats(FullTypeHints(List(classOf[MapWrap])))

        val ser = write(new MapWrap(Map[String,Any]("key" -> "value")))
        println("JSON: " + ser)
        println(read[MapWrap](ser))

    }
}

println(read[MapWrap](ser))导致投诉"net.liftweb.json.MappingException:数据无可用值."

The line println(read[MapWrap](ser)) results in the complaint "net.liftweb.json.MappingException: No usable value for data."

我如何反序列化此case类包装器(或实现我的最终目标:read(write(Map("key"->"value")))))?

How can I deserialize this case class wrapper (or achieve my ultimate goal: read(write(Map("key" -> "value"))))?

推荐答案

或者,您可以将case类参数设置为JObject并使用.values方法:

Alternatively, you can use set the case class params as JObject and use the .values method:

import org.junit.{Test, Assert, Before}
import org.junit.Assert._
import net.liftweb.json._

case class Element(title:String, params:JObject)
@Test
class JsonParserTest{
 implicit val formats = Serialization.formats(NoTypeHints)

 @Test
  def testLiftMapToAny{
    val result = parse("""{"title":"foobar","params":{"one":1,"two":2, "other": "give"}}""").extract[Element]

    assertEquals("foobar", result.title)
    assertEquals(Map("one" -> 1, "two" -> 2, "other" -> "give"), result.params.values)
  }
}

这篇关于使用带有lift-json的Map [String,Any]属性反序列化案例类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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