0

I have a question regarding System.Text.Json:

there are 2 Primary functions to deserialize:

MyClass deserialized = (MyClass)JsonSerializer.Deserialize(response, typeof(MyClass));
MyClass deserialized2 = JsonSerializer.Deserialize<MyClass>(response);

I wonder what the benefits of one over another are and in particular, if one is faster than the other.

julian bechtold
  • 1,875
  • 2
  • 19
  • 49
  • 2
    They are both the same. The Deserialize is just a wrapper for the first one – Tomasz Juszczak Dec 09 '22 at 16:09
  • 3
    And while `JsonSerialiser.Deserialize(string)` is simply a wrapper around `JsonSerializer.Deserialize(string, Type)`, it's certainly a lot easier to read (and type). – Mike Hofer Dec 09 '22 at 16:14
  • 1
    *I wonder what the benefits of one over another* -- `Deserialize` is cleaner when you know type `T` at compile time and are writing code that will use its members. This is the most common situation. `Deserialize(response, Type)` is useful when you are writing code that doesn't know the type at compile time, such as serialization middleware infrastructure. There should be no performance difference, but see https://ericlippert.com/2012/12/17/performance-rant/. – dbc Dec 09 '22 at 16:44

1 Answers1

1

The first method, JsonSerializer.Deserialize<T>(), is a generic method that allows you to specify the type you want to deserialize the JSON into as a type parameter. This can make your code more concise and easy to read.

The second method, JsonSerializer.Deserialize(), allows you to specify the type you want to deserialize the JSON into as a Type object. This can be useful if you don't know the type at compile time and need to use reflection to determine the type at runtime.

In terms of performance, both methods should be similar in terms of speed. If you want to ensure that your code is as efficient as possible, you should avoid using reflection unless it is absolutely necessary. In general, it's best to use the generic JsonSerializer.Deserialize<T>() method unless you have a specific reason to use the non-generic JsonSerializer.Deserialize() method.