Formatting DateTime in ASP.NET Core 3.0 using System.Text.Json

Solved with a custom formatter. Thank you Panagiotis for the suggestion. public class DateTimeConverter : JsonConverter<DateTime> { public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { Debug.Assert(typeToConvert == typeof(DateTime)); return DateTime.Parse(reader.GetString()); } public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options) { writer.WriteStringValue(value.ToUniversalTime().ToString(“yyyy’-‘MM’-‘dd’T’HH’:’mm’:’ssZ”)); } } // in the ConfigureServices() services.AddControllers() .AddJsonOptions(options => { … Read more

How to globally set default options for System.Text.Json.JsonSerializer?

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 … Read more

System.Text.Json: How to apply a JsonConverter for a collection with a custom converter for the collection’s items?

What you are looking for is the equivalent to Newtonsoft’s JsonPropertyAttribute.ItemConverterType: Gets or sets the JsonConverter type used when serializing the property’s collection items. Unfortunately, as of .NET 5 there is no directly equivalent attribute for System.Text.Json. Instead it will be necessary to introduce a JsonConverter decorator that serializes and deserializes collections and arrays using … Read more

Is there a simple way to manually serialize/deserialize child objects in a custom converter in System.Text.Json?

I figured it out. You simply pass your reader/writer down to another instance of the JsonSerializer and it handles it as if it were a native object. Here’s a complete example you can paste into something like RoslynPad and just run it. Here’s the implementation… using System; using System.Collections.ObjectModel; using System.Text.Json; using System.Text.Json.Serialization; public class … Read more

Getting nested properties with System.Text.Json

You could add a couple of extension methods that access a child JsonElement value by property name or array index, returning a nullable value if not found: public static partial class JsonExtensions { public static JsonElement? Get(this JsonElement element, string name) => element.ValueKind != JsonValueKind.Null && element.ValueKind != JsonValueKind.Undefined && element.TryGetProperty(name, out var value) ? … Read more

Custom JSON serializer for optional property with System.Text.Json

A custom JsonConverter<T> cannot prevent the serialization of a value to which the converter applies, see [System.Text.Json] Converter-level conditional serialization #36275 for confirmation. In .Net 5 there is an option to ignore default values which should do what you need, see How to ignore properties with System.Text.Json. This version introduces JsonIgnoreCondition.WhenWritingDefault: public enum JsonIgnoreCondition { … Read more

JsonSerializer.Deserialize fails

Your problem is that System.Text.Json is case-sensitive by default, so “id”: 9 (all lowercase) is not mapped to the Id property. From the docs: Case-insensitive property matching By default, deserialization looks for case-sensitive property name matches between JSON and the target object properties. To change that behavior, set JsonSerializerOptions.PropertyNameCaseInsensitive to true: Note: The web default … Read more

Is there a built in way of using snake case as the naming policy for JSON in ASP.NET Core 3?

Just slight modification in pfx code to remove the dependency on Newtonsoft Json.Net. String extension method to convert the given string to SnakeCase. public static class StringUtils { public static string ToSnakeCase(this string str) { return string.Concat(str.Select((x, i) => i > 0 && char.IsUpper(x) ? “_” + x.ToString() : x.ToString())).ToLower(); } } Then in our … Read more

Why does System.Text Json Serialiser not serialise this generic property but Json.NET does?

This is a documented limitation of System.Text.Json. From the docs: Serialize properties of derived classes In versions prior to .NET 7, System.Text.Json doesn’t support the serialization of polymorphic type hierarchies. For example, if a property is defined as an interface or an abstract class, only the properties defined on the interface or abstract class are … Read more

System.Text.Json: Deserialize JSON with automatic casting

Edit: You can use JsonNumberHandlingAttribute and it handles everything correctly in 1 line, no need to write any code: [JsonNumberHandling(JsonNumberHandling.AllowReadingFromString)] public class HomeController : Controller …. Original answer: The new System.Text.Json api exposes a JsonConverter api which allows us to convert the type as we like. For example, we can create a generic number to … Read more