map serialisation

78 views
Skip to first unread message

Michel Daviot

unread,
Jan 8, 2015, 5:51:29 PM1/8/15
to raptur...@googlegroups.com
Hi,

Is there a way to serialise directly a map like this one ?

val m=Map("a"->3, "b"->"c")

m: scala.collection.immutable.Map[String,Any] = Map(a -> 3, b -> c)

Json(m)

<console>:15: error: Cannot serialize type scala.collection.immutable.Map[String,Any] to rapture.json.Json. Please provide an implicit Serializer of type scala.collection.immutable.Map[String,Any].


I found a workaround using json interpolator like that :

 def toJsonObject: Json =
    json"""{ 
      "klass_id": $klassId, 
      "name":$name , 
      "cardstring":$cardString  }"""


But it might be possible to implement a serialiser for a Map[String, Any] by using proper serialisers based on runtime type and value.toString for the rest. What do you think ?

Jon Pretty

unread,
Jan 9, 2015, 1:29:18 PM1/9/15
to raptur...@googlegroups.com
Hi Michel,

That's not so straightforward because it relies on runtime types, so we'll have to create a custom serializer to dispatch to other serializers as appropriate. This works, but you'll need to add cases for all types you want to serialize:

  implicit val anySerializer: rapture.data.Serializer[Any, Json] =
    Json.serializer[Json].contramap {
      case s: String => Json(s)
      case i: Int => Json(i)
      case d: Double => Json(d)
    }

  val json = Json(Map("foo" -> "bar", "baz" -> 42))

That might look very redundant with the right-hand side of all the cases being the same, but each of those calls to `Json(foo)` is pulling in a different implicit `Serializer` of its own based on the type matched on the LHS.

Does that work?

Cheers,
Jon

--
You received this message because you are subscribed to the Google Groups "Rapture users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rapture-user...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.



--
Jon Pretty | @propensive

Michel Daviot

unread,
Jan 11, 2015, 7:27:17 PM1/11/15
to raptur...@googlegroups.com
Yep, that's fine, thanks a lot !
Reply all
Reply to author
Forward
0 new messages