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

2

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?

Monochromatism answered 16/10, 2015 at 22:18 Comment(0)
M
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

Mentality answered 18/10, 2015 at 7:32 Comment(0)
A
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)
Acrefoot answered 9/5, 2018 at 0:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.