Reputation: 44
I am working on a use-case where i am trying to built a web UI interface(using react and play framework) that takes Json/Json string as input and return Scala object that represents given json.
Input:
{
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
}
Output:
{SomeObjectName}(1,1,"delectus aut autem", false)
Here is my understanding, to get scala object from json we need scala object type. For example, we need class definition of MailServer as shown in this example
I found one example on how to convert json to case class in react using library: transform-json-types. Problem here is this library is in UI. If i have some library like this in scala that would be great but i couldn't find one. So, i am thinking to send generated case class definition from UI to backend as string and then extract case class in backend.
Few questions:
Any help is appreciated. Please point me in right direction.
Upvotes: 0
Views: 256
Reputation: 40500
The thing is, that even if you had a way to create (or somehow infer an existing definition) a case class on the fly, you wouldn't really be able to do much with it:
val foo = magicLibrary.readJson(fooJsonString)
What type is foo
above? It's gotta be Any
(or, maybe, AnyRef
). Even if magicLibrary
had a (magic) way of figuring out an constructing an actual class from given json, there is no way you can use that type downstream, because it is not going to be known at compile time.
The only thing you could do with that result is print it out, or, perhaps, convert back to json. But you already have json, so that's not useful.
Long story short, unless I completely misunderstood what you are asking, there is no library like this, and if there was one, it would not be of much use anyway.
What you can do in this case is just parse the the input into a Map[String, Any]
using one of the standard json libraries ... that may or may not be useful, depending on what it is you actually want to do with the result.
Better yet, rework your API to deal with actual known types.
Upvotes: 1