File size: 8,836 Bytes
fab29d7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
using System.Linq.Expressions;
using System.Reflection;
using System.Text.Json.Nodes;
using VersOne.Epub.Test.Integration.JsonUtils.Configuration;

namespace VersOne.Epub.Test.Integration.JsonUtils.Serializers
{
    internal class ObjectSerializer : TypeSerializer
    {
        private readonly Type objectType;
        private readonly CustomType? customType;
        private readonly TypeSerializerCollection typeSerializerCollection;
        private readonly Lazy<List<PropertySerializer>> propertySerializers;

        public ObjectSerializer(Type objectType, JsonSerializerConfiguration? jsonSerializerConfiguration, TypeSerializerCollection typeSerializerCollection)
        {
            this.objectType = objectType;
            customType = jsonSerializerConfiguration?.GetCustomType(objectType);
            this.typeSerializerCollection = typeSerializerCollection;
            propertySerializers = new Lazy<List<PropertySerializer>>(() => CreatePropertySerializers(objectType, customType, typeSerializerCollection));
        }

        public override JsonNode? Serialize(object? value, JsonSerializationContext jsonSerializationContext)
        {
            if (value == null)
            {
                return null;
            }
            else
            {
                JsonObject result = new();
                Type actualType = value.GetType();
                if (actualType != objectType)
                {
                    ObjectSerializer? actualTypeSerializer = typeSerializerCollection.GetSerializer(actualType) as ObjectSerializer;
                    Assert.NotNull(actualTypeSerializer);
                    actualTypeSerializer.SerializeIntoJsonObject(value, true, jsonSerializationContext, result);
                }
                else
                {
                    SerializeIntoJsonObject(value, false, jsonSerializationContext, result);
                }
                return result;
            }
        }

        private void SerializeIntoJsonObject(object value, bool writeTypeName, JsonSerializationContext jsonSerializationContext, JsonObject result)
        {
            if (customType?.PreserveReferences == true)
            {
                (int referenceNumber, bool isDuplicateReference) = jsonSerializationContext.GetReferenceNumber(value);
                if (isDuplicateReference)
                {
                    result.Add(Constants.DUPLICATE_REFERENCE_NUMBER_PROPERTY_NAME, referenceNumber);
                    return;
                }
                else
                {
                    result.Add(Constants.NEW_REFERENCE_NUMBER_PROPERTY_NAME, referenceNumber);
                }
            }
            if (writeTypeName)
            {
                result.Add(Constants.TYPE_PROPERTY_NAME, objectType.Name);
            }
            foreach (PropertySerializer propertySerializer in propertySerializers.Value)
            {
                JsonNode? serializedProperty;
                if (propertySerializer.ObtainCustomSerializer)
                {
                    if (jsonSerializationContext == null)
                    {
                        throw new ArgumentException($"JSON serialization context is required to serialize property {propertySerializer.TypePropertyName} in the type {objectType.Name}.");
                    }
                    serializedProperty = jsonSerializationContext.SerializePropertyValue(objectType, propertySerializer.TypePropertyName, value);
                }
                else
                {
                    serializedProperty = propertySerializer.Serialize(value, jsonSerializationContext);
                }
                if (serializedProperty != null || !propertySerializer.SkipPropertyIfValueIsNull)
                {
                    result.Add(propertySerializer.JsonPropertyName, serializedProperty);
                }
            }
        }

        private static List<PropertySerializer> CreatePropertySerializers(Type type, CustomType? customType, TypeSerializerCollection typeSerializerCollection)
        {
            List<PropertySerializer> result = new();
            foreach (PropertyInfo propertyInfo in type.GetRuntimeProperties())
            {
                string propertyName = propertyInfo.Name;
                CustomProperty? customProperty = customType?.GetCustomProperty(propertyName);
                if (customProperty != null)
                {
                    if (customProperty.UsesCustomSerialization)
                    {
                        result.Add(new PropertySerializer(propertyName, customProperty.JsonPropertyName,
                            (object _, JsonSerializationContext _) =>
                                throw new InvalidOperationException($"Custom serializer should be obtained for property {propertyName} in the type {type.Name}."),
                            skipPropertyIfValueIsNull: false, obtainCustomSerializer: true));
                        continue;
                    }
                    else if (customProperty.IsIgnored)
                    {
                        continue;
                    }
                }
                Type propertyType = propertyInfo.PropertyType;
                ParameterExpression inputParameterExpression = Expression.Parameter(typeof(object));
                Expression inputCastToTypeExpression = Expression.Convert(inputParameterExpression, type);
                MemberExpression getPropertyValueExpression = Expression.Property(inputCastToTypeExpression, propertyInfo);
                Expression propertyValueCastToObjectExpression = Expression.Convert(getPropertyValueExpression, typeof(object));
                Func<object, object?> propertyAccessor = Expression.Lambda<Func<object, object?>>(propertyValueCastToObjectExpression, inputParameterExpression).Compile();
                TypeSerializer propertyTypeSerializer = typeSerializerCollection.GetSerializer(propertyType);
                Func<object?, JsonSerializationContext, JsonNode?> propertyValueSerializer = propertyTypeSerializer.Serialize;
                JsonNode? propertySerializer(object @object, JsonSerializationContext jsonSerializationContext) =>
                    propertyValueSerializer(propertyAccessor(@object), jsonSerializationContext);
                PropertyDefaultValue? propertyDefaultValue = customProperty?.OptionalPropertyValue;
                if (propertyDefaultValue != null)
                {
                    JsonNode? optionalPropertySerializer(object @object, JsonSerializationContext jsonSerializationContext)
                    {
                        JsonNode? serializedProperty = propertySerializer(@object, jsonSerializationContext);
                        if (propertyDefaultValue?.HasFlag(PropertyDefaultValue.NULL) == true)
                        {
                            if (serializedProperty == null)
                            {
                                return null;
                            }
                        }
                        if (propertyDefaultValue?.HasFlag(PropertyDefaultValue.FALSE) == true)
                        {
                            if (serializedProperty is JsonValue serializedValue && serializedValue.TryGetValue(out bool booleanValue) && booleanValue == false)
                            {
                                return null;
                            }
                        }
                        if (propertyDefaultValue?.HasFlag(PropertyDefaultValue.EMPTY_ARRAY) == true)
                        {
                            if (serializedProperty is JsonArray serializedArray && serializedArray.Count == 0)
                            {
                                return null;
                            }
                        }
                        if (propertyDefaultValue?.HasFlag(PropertyDefaultValue.EMPTY_OBJECT) == true || propertyDefaultValue?.HasFlag(PropertyDefaultValue.EMPTY_DICTIONARY) == true)
                        {
                            if (serializedProperty is JsonObject serializedObject && serializedObject.Count == 0)
                            {
                                return null;
                            }
                        }
                        return serializedProperty;
                    }
                    result.Add(new PropertySerializer(propertyName, propertyName, optionalPropertySerializer, skipPropertyIfValueIsNull: true, obtainCustomSerializer: false));
                }
                else
                {
                    result.Add(new PropertySerializer(propertyName, propertyName, propertySerializer, skipPropertyIfValueIsNull: false, obtainCustomSerializer: false));
                }
            }
            return result;
        }
    }
}