-
Notifications
You must be signed in to change notification settings - Fork 532
/
Copy pathNewtonsoftJsonSerializer.cs
230 lines (201 loc) · 8.72 KB
/
NewtonsoftJsonSerializer.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
/*
Copyright 2017 Google Inc
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using Google.Apis.Util;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
namespace Google.Apis.Json
{
/// <summary>
/// A JSON converter which honers RFC 3339 and the serialized date is accepted by Google services.
/// </summary>
public class RFC3339DateTimeConverter : JsonConverter
{
/// <inheritdoc/>
public override bool CanRead => false;
/// <inheritdoc/>
public override object ReadJson(Newtonsoft.Json.JsonReader reader, Type objectType, object existingValue,
JsonSerializer serializer)
{
throw new NotImplementedException("Unnecessary because CanRead is false.");
}
/// <inheritdoc/>
public override bool CanConvert(Type objectType) =>
// Convert DateTime only.
objectType == typeof(DateTime) || objectType == typeof(Nullable<DateTime>);
/// <inheritdoc/>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (value != null)
{
DateTime date = (DateTime)value;
serializer.Serialize(writer, Utilities.ConvertToRFC3339(date));
}
}
}
/// <summary>
/// A JSON converter to write <c>null</c> literals into JSON when explicitly requested.
/// </summary>
public class ExplicitNullConverter : JsonConverter
{
/// <inheritdoc />
public override bool CanRead => false;
/// <inheritdoc />
public override bool CanConvert(Type objectType) => objectType.GetTypeInfo().GetCustomAttributes(typeof(JsonExplicitNullAttribute), false).Any();
/// <inheritdoc />
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException("Unnecessary because CanRead is false.");
}
/// <inheritdoc />
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) => writer.WriteNull();
}
/// <summary>
/// A JSON contract resolver to apply <see cref="RFC3339DateTimeConverter"/> and <see cref="ExplicitNullConverter"/> as necessary.
/// </summary>
/// <remarks>
/// Using a contract resolver is recommended in the Json.NET performance tips: https://www.newtonsoft.com/json/help/html/Performance.htm#JsonConverters
/// </remarks>
public class NewtonsoftJsonContractResolver : DefaultContractResolver
{
private static readonly JsonConverter DateTimeConverter = new RFC3339DateTimeConverter();
private static readonly JsonConverter ExplicitNullConverter = new ExplicitNullConverter();
/// <inheritdoc />
protected override JsonContract CreateContract(Type objectType)
{
JsonContract contract = base.CreateContract(objectType);
if (DateTimeConverter.CanConvert(objectType))
{
contract.Converter = DateTimeConverter;
}
else if (ExplicitNullConverter.CanConvert(objectType))
{
contract.Converter = ExplicitNullConverter;
}
return contract;
}
}
/// <summary>Class for serialization and deserialization of JSON documents using the Newtonsoft Library.</summary>
public class NewtonsoftJsonSerializer : IJsonSerializer
{
private readonly JsonSerializer serializer;
/// <summary>The default instance of the Newtonsoft JSON Serializer, with default settings.</summary>
public static NewtonsoftJsonSerializer Instance { get; } = new NewtonsoftJsonSerializer();
/// <summary>
/// Constructs a new instance with the default serialization settings, equivalent to <see cref="Instance"/>.
/// </summary>
public NewtonsoftJsonSerializer() : this(CreateDefaultSettings())
{
}
/// <summary>
/// Constructs a new instance with the given settings.
/// </summary>
/// <param name="settings">The settings to apply when serializing and deserializing. Must not be null.</param>
public NewtonsoftJsonSerializer(JsonSerializerSettings settings) =>
serializer = JsonSerializer.Create(Utilities.ThrowIfNull(settings, nameof(settings)));
/// <summary>
/// Creates a new instance of <see cref="JsonSerializerSettings"/> with the same behavior
/// as the ones used in <see cref="Instance"/>. This method is expected to be used to construct
/// settings which are then passed to <see cref="NewtonsoftJsonSerializer.NewtonsoftJsonSerializer(JsonSerializerSettings)"/>.
/// </summary>
/// <returns>A new set of default settings.</returns>
public static JsonSerializerSettings CreateDefaultSettings() =>
new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
ContractResolver = new NewtonsoftJsonContractResolver(),
};
/// <inheritdoc/>
public string Format => "json";
/// <inheritdoc/>
public void Serialize(object obj, Stream target)
{
using (var writer = new StreamWriter(target))
{
if (obj == null)
{
obj = string.Empty;
}
serializer.Serialize(writer, obj);
}
}
/// <inheritdoc/>
public string Serialize(object obj)
{
using (TextWriter tw = new StringWriter())
{
if (obj == null)
{
obj = string.Empty;
}
serializer.Serialize(tw, obj);
return tw.ToString();
}
}
/// <inheritdoc/>
public T Deserialize<T>(string input)
{
if (string.IsNullOrEmpty(input))
{
return default;
}
return (T)Deserialize(input, typeof(T));
}
/// <inheritdoc/>
public object Deserialize(string input, Type type)
{
if (string.IsNullOrEmpty(input))
{
return null;
}
using (JsonTextReader reader = new JsonTextReader(new StringReader(input)))
{
return serializer.Deserialize(reader, type);
}
}
/// <inheritdoc/>
public T Deserialize<T>(Stream input)
{
// Convert the JSON document into an object.
using (StreamReader streamReader = new StreamReader(input))
{
return (T)serializer.Deserialize(streamReader, typeof(T));
}
}
/// <summary>
/// Deserializes the given stream but reads from it asynchronously, observing the given cancellation token.
/// Note that this means the complete JSON is read before it is deserialized into objects.
/// </summary>
/// <typeparam name="T">The type to convert to.</typeparam>
/// <param name="input">The stream to read from.</param>
/// <param name="cancellationToken">Cancellation token for the operation.</param>
/// <returns>The deserialized object.</returns>
public async Task<T> DeserializeAsync<T>(Stream input, CancellationToken cancellationToken)
{
using (StreamReader streamReader = new StreamReader(input))
{
string json = await streamReader.ReadToEndAsync().WithCancellationToken(cancellationToken).ConfigureAwait(false);
using (var reader = new JsonTextReader(new StringReader(json)))
{
return (T) serializer.Deserialize(reader, typeof(T));
}
}
}
}
}