File size: 2,427 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
using System.Text.Json;
using System.Text.Json.Nodes;

namespace VersOne.Epub.Test.Integration.JsonUtils
{
    internal class JsonSerializationContext
    {
        private readonly Lazy<Dictionary<object, int>> serializationReferencedObjects;
        private readonly Lazy<Dictionary<int, object>> deserializationReferencedObjects;

        public JsonSerializationContext()
        {
            this.serializationReferencedObjects = new Lazy<Dictionary<object, int>>();
            this.deserializationReferencedObjects = new Lazy<Dictionary<int, object>>();
        }

        public (int referenceNumber, bool isDuplicateReference) GetReferenceNumber(object reference)
        {
            if (serializationReferencedObjects.Value.TryGetValue(reference, out int existingReferenceNumber))
            {
                return (existingReferenceNumber, true);
            }
            int newReferenceNumber = serializationReferencedObjects.Value.Count + 1;
            serializationReferencedObjects.Value.Add(reference, newReferenceNumber);
            return (newReferenceNumber, false);
        }

        public void AddReference(int referenceNumber, object reference)
        {
            if (deserializationReferencedObjects.Value.ContainsKey(referenceNumber))
            {
                throw new ArgumentException($"Reference ${referenceNumber} has already been added.");
            }
            deserializationReferencedObjects.Value[referenceNumber] = reference;
        }

        public object GetExistingReference(int existingReferenceNumber)
        {
            if (!deserializationReferencedObjects.Value.TryGetValue(existingReferenceNumber, out object? existingReference))
            {
                throw new ArgumentException($"Reference ${existingReferenceNumber} does not exist.");
            }
            return existingReference;
        }

        public virtual JsonNode? SerializePropertyValue(Type type, string propertyName, object serializingObject)
        {
            throw new NotImplementedException($"Custom type serializer is required to serialize an object of type {type.Name}");
        }

        public virtual object? DeserializePropertyValue(Type type, string propertyName, JsonElement serializedValue)
        {
            throw new NotImplementedException($"Custom type deserializer is required to deserialize an object of type {type.Name}");
        }
    }
}