Deserializing case classes with Map[String,Any] properties with lift-json

旧巷老猫 提交于 2019-12-04 05:57:18

This example works if you change your Map to Map[String, String]. Then the serializer knows you expect String values. Type hints are needed if your Map values are polymorphic. Like Map[String, Animal]; Dog extends Animal; Cat extends Animal etc. Now a type hint is required for Animal type. It adds "jsonClass" field to JSON which is used to decide the concrete target type.

If you can upgrade to 2.3-M1 then you no longer need to wrap the Map but can serialize the Map directly:

http://www.scala-tools.org/repo-releases/net/liftweb/lift-json_2.8.1/2.3-M1/

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