Conversion of Json String by converter vs deserialization

Viewed 409

I have a client server application where client sends data in json string format, when I receive the message I want this message to be converted to concrete type[defined in different assembly], here I have two options:

  1. use type converter to convert string to concrete type.
  2. use a deserializer to convert to concrete class. I tried to understand which option is better but could not get any concrete comparisons. Can anybody please explain the advantage and limitations of both?
2 Answers

If you are using Json by default, use deserialization.

The actual use of TypeConverter

  1. Convert between types, not necessarily between string and object. Any kind of object conversion is supported.
  2. Used in UIs to dynamically charge between string representations, mostly not JSON
  3. Used even in serialization libraries to handle custom types: https://www.newtonsoft.com/json/help/html/SerializationGuide.htm

When serializing a dictionary, the keys of the dictionary are converted to strings and used as the JSON object property names. The string written for a key can be customized by either overriding ToString() for the key type or by implementing a TypeConverter.

Serialization on the other hand:

Serialization is the process of converting an object into a stream of bytes to store the object or transmit it to memory, a database, or a file. Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called deserialization.

It's not about converting between types: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/serialization/

Since you are talking about transmission, then serialization is the way to go.

The idea to make a converter to convert JSON to that type is really bad. You would better use a JSON deserializer such as Newtonsoft.JSON or System.Text.Json which was significantly improved recently. I prefer using Newtonsoft.JSON, as it is less sensitive to input data, so, to convert a string to a type you need, you need simply to write something like tihs:

//Let's assume your type is Foo, and a string to deserialize is named json
Foo foo = JsonConvert.DeserializeObject<Foo>(json);

That's all! Now, your foo variable contains all the Foo class data, which was stored in json.

Using a deserializer is the best option, unless you need a really fast custom converter, if only you are sure that it will really faster.

P.S. If you are using ASP.NET as a server application, you don't even need to do something like this. Just put [FromBody] in your controller function, to convert a data stored in a request body, for example:

[HttpGet]
public void IActionResult GetFoo([FromBody] Foo foo)
{
//your code here
}

Hope that helped! ;)

Related