I have a problem. In our project the backend developers used different Enums then we did in our project, and we got a problem. We now need to serialize our object for them, changing will result for us rewrite the whole UI in .NET MAUI, so we want that to avoid. I am interested is there a way to write a custom Json Converter for System.Text.Json.
Here is my example:
public enum RenovationMode : byte
{
[Description("Beams")]
RoofTruss,
[Description("Slats")]
RoofTiles,
[Description("RoofStructure")]
CompleteRoofStructureReplacement,
[Description("Waterproofing")]
Waterproofing
}
So my idea was to put on every Enum value as description the value that is needed on server side as string (because they asked it as string). But, in converter I can't figure out how to read that.
public class EnumMapperJsonConverter : JsonConverter<string>
{
public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
throw new NotImplementedException();
}
public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options)
{
//how to read here the from the Enum the Description and return it as a string ?
}
}
Is this the right way to do this?
This code works for me
var myClass = new MyClass { Mode = RenovationMode.RoofTiles };
var json = System.Text.Json.JsonSerializer.Serialize(myClass);
output
{"Mode":"Slats"}
classes
public class MyClass
{
[System.Text.Json.Serialization.JsonConverter(typeof(EnumMapperJsonConverter))]
public RenovationMode Mode { get; set; }
}
public class EnumMapperJsonConverter : System.Text.Json.Serialization.JsonConverter<RenovationMode>
{
public override RenovationMode Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
throw new NotImplementedException();
}
public override void Write(Utf8JsonWriter writer, RenovationMode value, JsonSerializerOptions options)
{
writer.WriteStringValue(GetEnumDescription(value));
}
}
public static string GetEnumDescription(Enum value)
{
if (value == null) { return ""; }
DescriptionAttribute attribute = value.GetType()
.GetField(value.ToString())
?.GetCustomAttributes(typeof(DescriptionAttribute), false)
.SingleOrDefault() as DescriptionAttribute;
return attribute == null ? value.ToString() : attribute.Description;
}