C#C
C#3y ago
7 replies
Keyinator

❔ 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
string jsonNewMode = JsonConvert.SerializeObject(mode.AsSharedMode, new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.Auto });
//mode.AsSharedMode returns either S_Mode1 or S_Mode2 casted into an S_IMode

and then trying to deserialize
S_IMode s1 = JsonConvert.DeserializeObject<S_IMode>(value, new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.Auto });


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?
Was this page helpful?