-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHexStringJsonConverter.cs
37 lines (35 loc) · 1.1 KB
/
HexStringJsonConverter.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ImFlagger
{
public sealed class HexStringJsonConverter : JsonConverter<uint>
{
public override uint Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
var str = reader.GetString();
if (str == null || !str.StartsWith("0x") )
throw new JsonException($"Invalid hex string {str}");
try
{
return Convert.ToUInt32(str, 16);
}
catch (OverflowException ex)
{
throw new JsonException($"Too big hex number '{str}'");
}
catch (Exception ex)
{
throw new JsonException($"Invalid hex string '{str}'");
}
}
public override void Write(Utf8JsonWriter writer, uint value, JsonSerializerOptions options)
{
writer.WriteStringValue($"0x{value:X2}");
}
}
}