You can create an extension method. Here's an example
I use separate methods vs having to build special settings, so that all the settings will be in a single spot and easily reusable.
public static class DeserializeExtensions
{
private static JsonSerializerOptions defaultSerializerSettings = new JsonSerializerOptions();
// set this up how you need to!
private static JsonSerializerOptions featureXSerializerSettings = new JsonSerializerOptions();
public static T Deserialize<T>(this string json)
{
return JsonSerializer.Deserialize<T>(json, defaultSerializerSettings);
}
public static T DeserializeCustom<T>(this string json, JsonSerializerOptions settings)
{
return JsonSerializer.Deserialize<T>(json, settings);
}
public static T DeserializeFeatureX<T>(this string json)
{
return JsonSerializer.Deserialize<T>(json, featureXSerializerSettings);
}
}
Then you call it as a method on a string, whether literal or a variable.
Car result = @"{""Wheels"": 4, ""Doors"": 2}".DeserializeFeatureX<Car>();
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…