hmil / RosHTTP

Unified Scala.js + Scala HTTP client API
MIT License
126 stars 24 forks source link

Case classes to json automatically #55

Closed visox closed 8 years ago

visox commented 8 years ago

I don't like to rewrite case classes into json like this:

val jsonData = JSONObject(
  "answer" -> 42,
  "platform" -> "node"
)

It smells and i am also loosing some typesafety (lets say i have some structure that i share with backend and frontend)

There are many json parsers/solutions that do that, so its hopefully not too hard.

hmil commented 8 years ago

Hi @visox,

Thank you for your feedback. Could you elaborate what you don't like about the code above and what you'd like to be able to do instead?

Also when you say loosing some typesafety are you talking about typing constraints within your JSON structure (in your example answer: number, platform: string)? The JSON AST provided with RosHTTP is extremely basic and does not support this kind of internal constraints.

If you wish to use some more advanced JSON library, I'd advise you to create a subclass of BulkBodyPart, return the string you obtain from the JSON library of your choice as a UTF-8 encoded ByteBuffer and define the Content-Type member as application/json; charset=utf-8 (see the implementation of JSONBody for example.

Issue #29 might be relevant to your case.

visox commented 8 years ago

hi

what you'd like to be able to do instead?

val jsonData = someCaseClassInstance.toJs

would be best. Including some default implicit write functions that one could still override

you talking about typing constraints within your JSON structure

yes

RosHTTP is extremely basic and does not support this kind of internal constraints

i see :/

Thx for the suggestions.

hmil commented 8 years ago

AFAIK transforming class structures to program data always involves reflectivity in Java which goes way beyond the scope of this library. I'm interested to know if there is a clean way to achieve this in Scala as #29 should keep the door open for a solution to your use case, if not solve it directly.