0

I send JSON objects from a client to a server. In the server I need to do some action based on the object type. I could send a filed type in every request then try to parse JSON against base Message class:

public class Message
{
   string type { get; set; }
}

...
JsonSerializer.Deserialize<Message>(data);

then read the type and deserialize again:

public class SpecificMessage : Message
{
    public string command;
}

var message = JsonSerializer.Deserialize<SpecificMessage>(data);

But it requires the data to be parsed twice.

I thought about solution like adding message type in front of JSON message but then thought that maybe it's not worth to reinvent the wheel.

King King
  • 61,710
  • 16
  • 105
  • 130
user2146414
  • 840
  • 11
  • 29
  • If you are using Json.NET, [this answer](https://stackoverflow.com/a/19308474) might help you. – Mario Welzig Mar 14 '21 at 23:25
  • 1
    @MarioWelzig he's definitely using `System.Text.Json`, not the newtonsoft json. Also if using json.net, he has one option to serialize the type info (as `$type` property). For the converter, if implemented incorrectly, I think it's almost like deserializing twice, as in the code from the link you shared, we have this `JObject.Load(reader)` which is the core deserialization, all json content is still loaded into token and read later for actually deserializing to the result of a specific type. It's of course always more convenient and faster than the OP's current solution. – King King Mar 14 '21 at 23:35
  • Do [Is polymorphic deserialization possible in System.Text.Json?](https://stackoverflow.com/q/58074304/3744182), [System.Text.Json and Dynamically Parsing polymorphic objects](https://stackoverflow.com/q/60792311/3744182) and/or [Is there a simple way to manually serialize/deserialize child objects in a custom converter in System.Text.Json?](https://stackoverflow.com/q/59743382/3744182) answer your question? If you ensure that the `type` property appears first in your JSON object, or that the type is used as a property name for the actual values, you can avoid the double parsing. – dbc Mar 15 '21 at 15:09

0 Answers0