-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRTEJsonConverter.cs
More file actions
83 lines (82 loc) · 3.43 KB
/
RTEJsonConverter.cs
File metadata and controls
83 lines (82 loc) · 3.43 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
71
72
73
74
75
76
77
78
79
80
81
82
83
using System;
using System.Linq;
using System.Reflection;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Contentstack.Utils.Converters
{
public class RTEJsonConverter : JsonConverter<object>
{
public override bool CanConvert(Type typeToConvert)
{
return true;
}
public override object Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
using (var jsonDoc = JsonDocument.ParseValue(ref reader))
{
var root = jsonDoc.RootElement;
object targetObj = Activator.CreateInstance(typeToConvert);
foreach (PropertyInfo prop in typeToConvert.GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
var attr = prop.GetCustomAttribute<JsonPropertyNameAttribute>();
string jsonPath = attr != null ? attr.Name : prop.Name;
JsonElement token = root;
bool found = false;
// Support nested property names like 'system.uid'
if (jsonPath.Contains("."))
{
var parts = jsonPath.Split('.');
JsonElement current = root;
foreach (var part in parts)
{
if (current.ValueKind == JsonValueKind.Object && current.TryGetProperty(part, out var next))
{
current = next;
found = true;
}
else
{
found = false;
break;
}
}
if (found)
token = current;
}
else if (root.TryGetProperty(jsonPath, out var directToken))
{
token = directToken;
found = true;
}
if (found)
{
object value = JsonSerializer.Deserialize(token.GetRawText(), prop.PropertyType, options);
prop.SetValue(targetObj, value);
}
else
{
// Set default value for missing properties
if (prop.PropertyType.IsValueType)
prop.SetValue(targetObj, Activator.CreateInstance(prop.PropertyType));
else
prop.SetValue(targetObj, null);
}
}
return targetObj;
}
}
public override void Write(Utf8JsonWriter writer, object value, JsonSerializerOptions options)
{
writer.WriteStartObject();
foreach (PropertyInfo prop in value.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
var attr = prop.GetCustomAttribute<JsonPropertyNameAttribute>();
string jsonPath = attr != null ? attr.Name : prop.Name;
writer.WritePropertyName(jsonPath);
JsonSerializer.Serialize(writer, prop.GetValue(value), options);
}
writer.WriteEndObject();
}
}
}