How to have a generic solution to parse an unknown class to Json in scalaJs

86 views Asked by At

I'm using ScalaJs angular and Upickle and I try to create a filter to transform an unknown class to JSON.

What I tried :

my scope :

var myScope: MyClass = js.native

my filter:

@injectable("copy")
class CopyFilter extends Filter[Any] {

  override def filter(any: Any): js.Dynamic = {
    val myClass = any.getClass
    fromClassToJsValue[myClass](any)
  }
}

my function

def fromClassToJsValue[A](value: A)(implicit serializer: Writer[A]): js.Dynamic =
JSON.parse(write(value))

In this case my problem is getClass which returns Class[_] and not MyClass

Is there any solution to find MyClass? (Or maybe any other solution to derive a type Any?)

1

There are 1 answers

0
Justin du Coeur On

Broadly speaking, uPickle isn't designed to deal with that; I don't think any of the other JSON serializers are, either. That sort of Any-friendly serialization is usually based on reflection, which mostly isn't available in the JavaScript environment.

I suspect you do need a Filter per case class, albeit probably a one-liner. (Possibly done as a base trait that you mix into the case classes themselves, but I don't know Angular, so I know don't what the constraints look like.)