microsoft/teams.net

Public

mirrored fromhttps://github.com/microsoft/teams.netAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
affd7569cfa8bd4a83b86066b8636721ea186364

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

Libraries/Microsoft.Teams.Common/Json/JsonObjectExtensions.cs

72lines · modecode

1using System.Reflection;
2using System.Text.Json;
3using System.Text.Json.Nodes;
4using System.Text.Json.Serialization;
5
6namespace Microsoft.Teams.Common.Json;
7
8public static partial class JsonObjectExtensions
9{
10 public static IDictionary<string, object?> FromJsonObject<T>(this T value, JsonObject json, JsonSerializerOptions? options = null) where T : notnull
11 {
12 var properties = value.GetType().GetProperties();
13 var other = new Dictionary<string, object?>();
14
15 foreach (var pair in json)
16 {
17 var property = properties.FirstOrDefault(f =>
18 pair.Key == (f.GetCustomAttribute<JsonPropertyNameAttribute>()?.Name ?? f.Name)
19 );
20
21 if (property is null)
22 {
23 other[pair.Key] = pair.Value.Deserialize<object>(options);
24 continue;
25 }
26
27 if (property.GetCustomAttribute<JsonIgnoreAttribute>() is not null)
28 {
29 continue;
30 }
31
32 property.SetValue(value, pair.Value.Deserialize(property.PropertyType, options));
33 }
34
35 return other;
36 }
37
38 public static JsonObject ToJsonObject(this object value, JsonSerializerOptions? options = null)
39 {
40 var json = new JsonObject();
41 var properties = value
42 .GetType()
43 .GetProperties()
44 .OrderBy(p => p.GetCustomAttribute<JsonPropertyOrderAttribute>()?.Order ?? p.MetadataToken);
45
46 foreach (var property in properties)
47 {
48 var propertyName = property.GetCustomAttribute<JsonPropertyNameAttribute>()?.Name ?? property.Name;
49 var propertyValue = property.GetValue(value);
50
51 if (property.GetCustomAttribute<JsonIgnoreAttribute>() is not null) continue;
52 if (propertyValue is null) continue;
53 if (property.GetCustomAttribute<JsonExtensionDataAttribute>() is not null)
54 {
55 var jsonObject = JsonSerializer.SerializeToNode(propertyValue, propertyValue.GetType(), options)?.AsObject();
56
57 if (jsonObject is null) continue;
58
59 foreach (var item in jsonObject)
60 {
61 json.Add(item.Key, item.Value?.DeepClone());
62 }
63
64 continue;
65 }
66
67 json.Add(propertyName, JsonSerializer.SerializeToNode(propertyValue, options));
68 }
69
70 return json;
71 }
72}