5

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?

Community
  • 1
  • 1
nvalada
  • 265
  • 1
  • 11

2 Answers2

6
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

gurghet
  • 7,591
  • 4
  • 36
  • 63
Li Haoyi
  • 15,330
  • 17
  • 80
  • 137
1

The answer above no longer applies for newer versions of upickle. In version 0.6.5 I had to use the following to deserialize a dynamic object:

val someJsObject: js.Dynamic = ...
upickle.WebJson.transform(someJsObject, implicitly[upickle.default.Reader[TargetType]])

To serialize, you will probably want something like:

val sourceObject: SourceType = ...
implicitly[upickle.default.Writer[SourceType]].write(upickle.WebJson.Builder, sourceObject)
Chris Dow
  • 29
  • 1