System.Text.Json.JsonSerializer.Serialize
is a set of overloads that serialize a C# object into json.
The non-generic overloads all share three parameters - object? value
which is the object to serialize; System.Text.Json.JsonSerializerOptions? options
, which allows configuring the serializer with respect to all kinds of choices, and Type inputType
, which is what this question is about.
inputType
is merely described as "The type of the value to convert." However, what does that actually mean and do? Is there a meaningful difference between typeof(object)
in this context and value.GetType()
?
I peeked into the code, but it quickly became clearly this isn't a simple matter; the type helps resolve a JsonTypeInfo, but e.g. typeof(object) is special-cased there.
I did a few quick-and dirty benchmarks:
using System.Security.Cryptography;
using System.Text.Json;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
BenchmarkRunner.Run<JsonBench>();
sealed record Bla(string Foo, int Bar);
public class JsonBench
{
readonly Bla value = new Bla("a", 2);
[Benchmark]
public string WithGenerics() => JsonSerializer.Serialize(value);
[Benchmark]
public string WithGetType() => JsonSerializer.Serialize(value, value.GetType());
[Benchmark]
public string WithObjectType() => JsonSerializer.Serialize(value, typeof(object));
readonly Type cachedObject = typeof(object), cachedBla = typeof(Bla);
[Benchmark]
public string WithCachedGetType() => JsonSerializer.Serialize(value, cachedBla);
[Benchmark]
public string WithCachedObjectType() => JsonSerializer.Serialize(value, cachedObject);
}
...and for small objects there appears to be very slight (on the order of 10ns) overhead from using typeof(object)
. Is that it? Are there corner cases where this is more? If using value.GetType()
is reliably faster... why does this choice even exist all?
In short: I'm not sure I understand the purpose of this Type inputType
parameter.
Can anybody clarify what this is actually for?