Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serialize/deserialize case class to js.Dynamic with uPickle

I am using uPickle/ScalaJS to deserialize a js.Dynamic object into a case class using this code fragment:

read[myClass](JSON.stringify(dynObj))

where myClass is the case class and dynObj is the js.Dynamic object.

Is there a boilerplate-free and simpler way to do this?

In order to serialize a case class, I have been able to serialize to js.Dynamic using Shapeless using this example as a starting point:

Converting nested case classes to nested Maps using Shapeless

I would like to be able to use uPickle to do this instead. How can I accomplish the round-trip with uPickle?

like image 310
nvalada Avatar asked Oct 16 '15 22:10

nvalada


1 Answers

upickle.default.readJs[myClass](upickle.json.readJs(dynObj))

Should do it. You can wrap it in a nice helper if you find yourself doing it a lot.

Similar calls exist to write things to js.Dynamic, just the other way round

 upickle.json.writeJs(upickle.default.writeJs[myClass](myClassInstance))

Though you can probably leave out the type parameter here since it'll be inferred

like image 80
Li Haoyi Avatar answered Sep 19 '22 15:09

Li Haoyi