using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Collections.ObjectModel;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Metadata;
using System.Text.Json.Nodes;
[JsonConverter(typeof(FooModelJsonConverter))]
public enum State { STARTED, RUNNING, COMPLETED, FAILED };
public Guid Id { get; set; }
public string? AnotherId { get; set; }
public string? Name { get; set; }
[JsonConverter(typeof(JsonStringEnumConverter))]
public State Status { get; set; }
public int? MajorVersion { get; set; } = 1;
public int? MinorVersion { get; set; } = 0;
public class FooModelJsonConverter: JsonConverter<FooModel>
public override FooModel Read(
ref Utf8JsonReader reader,
JsonSerializerOptions options
JsonSerializer.Deserialize<FooModel>(ref reader, options)
?? throw new JsonException("FooModel could not be deserialized as it was null!");
public override void Write(
JsonSerializerOptions options
writer.WriteStartObject();
var majorVersion = fooModel.MajorVersion;
var minorVersion = fooModel.MinorVersion;
if (majorVersion == null || minorVersion == null)
$"Expected a 'Major' & 'Minor' attribute but one (or both) of them is null => MajorVersion: {majorVersion}\nMinorVersion: {minorVersion}!"
writer.WritePropertyName(TryParseCamelCase(nameof(fooModel.Id), options, true));
JsonSerializer.Serialize(writer, fooModel.Id, options);
writer.WritePropertyName(TryParseCamelCase(nameof(fooModel.AnotherId), options, true));
JsonSerializer.Serialize(writer, fooModel.AnotherId, options);
throw new JsonException($"Unexpected 'Minor' version attribute: {minorVersion}");
writer.WritePropertyName(TryParseCamelCase(nameof(fooModel.Name), options, true));
JsonSerializer.Serialize(writer, fooModel.Name, options);
writer.WritePropertyName(TryParseCamelCase(nameof(fooModel.Status), options, true));
JsonSerializer.Serialize(writer, fooModel.Status, options);
throw new JsonException($"Unexpected 'Major' version attribute: {majorVersion}");
public static string TryParseCamelCase(string propertyName, JsonSerializerOptions options, bool disabled = false)
var namingPolicy = options.PropertyNamingPolicy;
return namingPolicy != null ? namingPolicy.ConvertName(propertyName) : propertyName;
public static void Test()
AnotherId = "another id",
Status = FooModel.State.RUNNING,
var options = new JsonSerializerOptions
Converters = { new FooModelJsonConverter() },
var json = JsonSerializer.Serialize(foo, options);
public static void Main()
Console.WriteLine("Environment version: {0} ({1}), {2}", System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription , Environment.Version, Environment.OSVersion);
Console.WriteLine("System.Text.Json version: " + typeof(JsonSerializer).Assembly.FullName);
Console.WriteLine("Failed with unhandled exception: ");