Vineet Goel
Vineet Goel

Reputation: 2148

Scala ListMap deserialization using jackson

I am trying to serialize and then deserialize a Scala immutable ListMap using Jackson.

I define val foo: ListMap[String, String] = ListMap("foo1" -> "bar1", "foo2" -> "bar2") and then serialize it using jackson. I verified the serialized string and it looked fine. Then when I try to deserialize the string using Jackson, I get the following error:

java.lang.ClassCastException: scala.collection.immutable.Map$Map1 cannot be cast to scala.collection.immutable.ListMap
    at .<init>(<console>:12)
    at .<clinit>(<console>)
    at .<init>(<console>:7)
    at .<clinit>(<console>)
    at $print(<console>)

Any idea how to effectively serialize/deserialize ListMaps?

Upvotes: 0

Views: 438

Answers (1)

Kordi
Kordi

Reputation: 2465

Code

The code for Serializing ListMap is

val mapper = new ObjectMapper
mapper.registerModule(DefaultScalaModule)
val m = ListMap((5, 1), (2, 33), (7, 22), (8, 333))
mapper.writeValueAsString(m)

Deserializing is

val str = """{"5":1,"2":33,"7":22,"8":333}"""
val listMap:ListMap = objectMapper.readValue[ListMap](str)

with the same Initializing of the mapper like in the serialization example.

Output

For serialization

{"5":1,"2":33,"7":22,"8":333}

For deserialization

Map(5 -> 1, 2 -> 33, 7 -> 22, 8 -> 333)

Upvotes: 2

Related Questions