-
Notifications
You must be signed in to change notification settings - Fork 186
Expand file tree
/
Copy pathEncodingJsonConverter.cs
More file actions
70 lines (60 loc) · 2.33 KB
/
EncodingJsonConverter.cs
File metadata and controls
70 lines (60 loc) · 2.33 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
using System.Text;
using Newtonsoft.Json;
namespace LogExpert.Core.Classes.JsonConverters;
/// <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);
}
/// <summary>
/// Serializes the Encoding object to its name.
/// </summary>
/// <param name="writer"></param>
/// <param name="value"></param>
/// <param name="serializer"></param>
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);
}
/// <summary>
/// Reads a JSON value and converts it to an <see cref="Encoding"/> object.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> to read from. Cannot be <see langword="null"/>.</param>
/// <param name="objectType">The type of the object to deserialize. This parameter is not used in this method.</param>
/// <param name="existingValue">The existing value of the object being deserialized. This parameter is not used in this method.</param>
/// <param name="serializer">The calling serializer. This parameter is not used in this method.</param>
/// <returns>An <see cref="Encoding"/> object corresponding to the JSON value. Returns <see cref="Encoding.Default"/> if the
/// JSON value is <see langword="null"/>, empty, or an invalid encoding name.</returns>
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;
}
}
}