❔ Using JsonConvert to send over interface
Hello everyone,
after long times of googling I sadly haven't found any solution to a jsonconvert problem with interfaces.
I have three projects:
Client
, Server
, Shared
. Both Client
and Server
can access Shared
.
In the shared project I have the following classes: S_Mode1:S_IMode
, S_Mode2:S_IMode
which inherit from the interface S_IMode
Now my goal is to serialize these classes using JsonConvert
and send them from the server to the client.
My idea is to send them as an S_IMode
so that on the client I can use them as expected and still differentiate between S_Mode1
and S_Mode1
I am currently serializing this into a string from the server using
and then trying to deserialize
Sadly this fails with
Newtonsoft.Json.JsonSerializationException: Could not create an instance of type GCShared.NewModus.Networking.S_IMode. Type is an interface or abstract class and cannot be instantiated. Path 'Id', line 1, position 6.
Any tips what I can do?5 Replies
As the error suggests, you can't create new instances of interfaces or abstract classes
Why do you want to deserialize as an interface?
This is code for a gameserver which has multiple modes. Depending on the mode the player is in it functions will perform differently.
I have a Property
current_mode
which is used for all of that. Now depending on the underlying class that current_mode is, the functions will perform differently.
So now to put that information from the server to the client, I wanted to send it via the method above.Okay, best option would be to send a flag that determines the mode before the deserialization
a better solution is to properly model your data
Depending on the mode the player is in it functions will perform differently.data shouldn't be performing functions, data should be data if your data can vary depending on what mode the server is running in, and you need interfaces to handle that, you haven't properly modeled your data
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.