-
Notifications
You must be signed in to change notification settings - Fork 186
Expand file tree
/
Copy pathEncodingJsonConverter.cs
More file actions
53 lines (45 loc) · 1.31 KB
/
EncodingJsonConverter.cs
File metadata and controls
53 lines (45 loc) · 1.31 KB
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
using System.Text;
using Newtonsoft.Json;
namespace LogExpert.Core.Classes.Persister;
/// <summary>
/// Custom JsonConverter for Encoding objects.
/// Serializes the encoding as its name (e.g. "utf-8").
/// </summary>
public class EncodingJsonConverter : JsonConverter
{
public override bool CanConvert (Type objectType)
{
return typeof(Encoding).IsAssignableFrom(objectType);
}
public override void WriteJson (JsonWriter writer, object? value, JsonSerializer serializer)
{
ArgumentNullException.ThrowIfNull(writer);
if (value is not Encoding encoding)
{
writer.WriteNull();
return;
}
writer.WriteValue(encoding.WebName);
}
public override object? ReadJson (JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{
ArgumentNullException.ThrowIfNull(reader);
if (reader.TokenType == JsonToken.Null)
{
return null;
}
var encodingName = reader.Value?.ToString();
if (string.IsNullOrEmpty(encodingName))
{
return Encoding.Default;
}
try
{
return Encoding.GetEncoding(encodingName);
}
catch (ArgumentException)
{
return Encoding.Default;
}
}
}