-
Notifications
You must be signed in to change notification settings - Fork 494
/
CosmosSystemTextJsonSerializer.cs
80 lines (69 loc) · 2.92 KB
/
CosmosSystemTextJsonSerializer.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
namespace Cosmos.Samples.Shared
{
using System.IO;
using System.Reflection;
using System.Text.Json;
using System.Text.Json.Serialization;
using Azure.Core.Serialization;
using Microsoft.Azure.Cosmos;
/// <summary>
/// Uses <see cref="Azure.Core.Serialization.JsonObjectSerializer"/> which leverages System.Text.Json providing a simple API to interact with on the Azure SDKs.
/// </summary>
/// <remarks>
/// For item CRUD operations and non-LINQ queries, implementing CosmosSerializer is sufficient. To support LINQ query translations as well, CosmosLinqSerializer must be implemented.
/// </remarks>
// <SystemTextJsonSerializer>
public class CosmosSystemTextJsonSerializer : CosmosLinqSerializer
{
private readonly JsonObjectSerializer systemTextJsonSerializer;
private readonly JsonSerializerOptions jsonSerializerOptions;
public CosmosSystemTextJsonSerializer(JsonSerializerOptions jsonSerializerOptions)
{
this.systemTextJsonSerializer = new JsonObjectSerializer(jsonSerializerOptions);
this.jsonSerializerOptions = jsonSerializerOptions;
}
public override T FromStream<T>(Stream stream)
{
using (stream)
{
if (stream.CanSeek
&& stream.Length == 0)
{
return default;
}
if (typeof(Stream).IsAssignableFrom(typeof(T)))
{
return (T)(object)stream;
}
return (T)this.systemTextJsonSerializer.Deserialize(stream, typeof(T), default);
}
}
public override Stream ToStream<T>(T input)
{
MemoryStream streamPayload = new MemoryStream();
this.systemTextJsonSerializer.Serialize(streamPayload, input, input.GetType(), default);
streamPayload.Position = 0;
return streamPayload;
}
public override string SerializeMemberName(MemberInfo memberInfo)
{
JsonExtensionDataAttribute jsonExtensionDataAttribute = memberInfo.GetCustomAttribute<JsonExtensionDataAttribute>(true);
if (jsonExtensionDataAttribute != null)
{
return null;
}
JsonPropertyNameAttribute jsonPropertyNameAttribute = memberInfo.GetCustomAttribute<JsonPropertyNameAttribute>(true);
if (!string.IsNullOrEmpty(jsonPropertyNameAttribute?.Name))
{
return jsonPropertyNameAttribute.Name;
}
if (this.jsonSerializerOptions.PropertyNamingPolicy != null)
{
return this.jsonSerializerOptions.PropertyNamingPolicy.ConvertName(memberInfo.Name);
}
// Do any additional handling of JsonSerializerOptions here.
return memberInfo.Name;
}
}
// </SystemTextJsonSerializer>
}