JSON.NET supports deserializing hexadecimal numbers (e.g. 0xffff), but how about serializing?
The following works, but seems far too complicated:
public sealed class HexJsonConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return typeof(uint).Equals(objectType);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteRawValue($"0x{value:x}");
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override bool CanRead => false;
}
I am looking for something along the lines of DateFormatHandling, only for integers.
JsonTextReaderfor Newtonsoft.Json handles many more behind-the-scenes conversions compared to theJsonTextWriter. The JSON format doesn't support hexadecimal, so I would put the value inside a string. What you have works otherwise.JsonTextWriterand override methods likeJsonTextWriter.WriteValue(Int32). Hex format numbers explicitly violate the JSON standard (unlike dates for which there is no official JSON representation) which may be why hex format output is not built-in.