Dynamic data recibe on method ON
Closed this issue · 9 comments
Hello, is there a way to generate an array if a string, JSON, or other types are received? I am creating a plugin for NativeScript and the data received is dynamic. Is it possible?
Can you describe your scenario in more detail? I haven't worked with NativeScript so don't understand how SignalR fits there.
In general this client doesn't provide access to the raw JSON received from the server (or parts of it). In SignalR, the handlers need to correspond to how the server invokes these handlers, so building something that would work for any server seems challenging.
@moozzyk Hi, I am creating a plugin for NativeScript, and in Swift, it's almost ready. I still need to deserialize the data that arrives in on("my_event", data) and thus be able to generate an array if data is an array, a string if data is a string, and so on with each of the types. But I am using Swift, and from there I call the Swift functions from NativeScript, and I need to know how to convert that event data in Swift and pass it to a type compatible with TypeScript.
Do you control the server? If so, you could send your data as a string from the server as the argument and then decode it to a string on the client and then deal with it. Other than that I don't know of an easy way achieving what you want.
@moozzyk I don't have access to the server, and since this is a plugin, it should be possible to deserialize the received data.
Here are a couple of ideas (note I have not tried any of these so YMMV):
- try using AnyDecodable type for your argument
- do something similar yourself by using the
ArgumentExtractor .getArgument
method.
For the second option you wouldn't use the strongly typed on
extensions but would have to create your own that has a customized callback that tries to decode to a different target type. For references here is how the extensions look like. If you look at the callback, it decodes for the target type. Your callback would have to try different types, similarly to what the AnyDecodable
(option 1) does.
Using https://github.com/SwiftyJSON/SwiftyJSON, erasing primitive types
@jiasongs Does it work with an array of objects?
thanks @moozzyk and @jiasongs