-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathStringified.cs
90 lines (67 loc) · 2.63 KB
/
Stringified.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
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
// Licensed to Elasticsearch B.V under one or more agreements.
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Elastic.Clients.Elasticsearch.Serialization;
internal sealed class StringifiedLongConverter : JsonConverter<long?>
{
public override long? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) => ReadStringifiedLong(ref reader);
public override void Write(Utf8JsonWriter writer, long? value, JsonSerializerOptions options) => writer.WriteNumberValue(value.Value);
public static long ReadStringifiedLong(ref Utf8JsonReader reader)
{
if (reader.TokenType == JsonTokenType.PropertyName)
reader.Read();
if (reader.TokenType == JsonTokenType.String)
{
var longString = reader.GetString();
if (!long.TryParse(longString, out var longValue))
{
throw new JsonException("Unable to parse string value to long.");
}
return longValue;
}
return reader.GetInt64();
}
}
internal sealed class StringifiedIntegerConverter : JsonConverter<int?>
{
public override int? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) => ReadStringifiedInteger(ref reader);
public override void Write(Utf8JsonWriter writer, int? value, JsonSerializerOptions options) => writer.WriteNumberValue(value.Value);
public static int ReadStringifiedInteger(ref Utf8JsonReader reader)
{
if (reader.TokenType == JsonTokenType.PropertyName)
reader.Read();
if (reader.TokenType == JsonTokenType.String)
{
var intString = reader.GetString();
if (!int.TryParse(intString, out var intValue))
{
throw new JsonException("Unable to parse string value to integer.");
}
return intValue;
}
return reader.GetInt32();
}
}
internal sealed class StringifiedBoolConverter : JsonConverter<bool?>
{
public override bool? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) => ReadStringifiedBool(ref reader);
public override void Write(Utf8JsonWriter writer, bool? value, JsonSerializerOptions options) => writer.WriteBooleanValue(value.Value);
public static bool ReadStringifiedBool(ref Utf8JsonReader reader)
{
if (reader.TokenType == JsonTokenType.PropertyName)
reader.Read();
if (reader.TokenType == JsonTokenType.String)
{
var boolString = reader.GetString();
if (!bool.TryParse(boolString, out var boolValue))
{
throw new JsonException("Unable to parse string value to bool.");
}
return boolValue;
}
return reader.GetBoolean();
}
}