JSON.NET支持deserializing hexadecimal numbers(例如0xffff
),但序列化怎么样?
以下作品,但似乎太复杂了:
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;
}
我正在寻找符合DateFormatHandling的内容,仅适用于整数。
答案 0 :(得分:3)
正如评论中所指出的,JSON中不允许使用十六进制文字(与JavaScript相反)。
将uint
值转换为十六进制字符串文字,反之亦然:
public sealed class HexStringJsonConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return typeof(uint).Equals(objectType);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteValue($"0x{value:x}");
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var str = reader.ReadAsString();
if (str == null || !str.StartsWith("0x"))
throw new JsonSerializationException();
return Convert.ToUInt32(str);
}
}
public sealed class CanonInfo
{
[JsonConverter(typeof(HexStringJsonConverter))]
public uint ModelId { get; set; }
[JsonConverter(typeof(HexStringJsonConverter))]
public uint FirmwareRevision { get; set; }
}
答案 1 :(得分:0)
以下代码适用于HexJsonConverter
类
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if(reader.ValueType.FullName == typeof(string).FullName)
{
string str = (string)reader.Value;
if (str == null || !str.StartsWith("0x"))
throw new JsonSerializationException();
return Convert.ToUInt32(str.Substring("0x".Length), 16);
}
else
throw new JsonSerializationException();
}