forked from Havunen/SystemTextJsonPatch
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDictionaryPropertyProxy.cs
More file actions
88 lines (78 loc) · 1.88 KB
/
Copy pathDictionaryPropertyProxy.cs
File metadata and controls
88 lines (78 loc) · 1.88 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
84
85
86
87
88
using System;
using System.Collections;
using SystemTextJsonPatch.Exceptions;
namespace SystemTextJsonPatch.Internal.Proxies
{
internal sealed class DictionaryPropertyProxy : IPropertyProxy
{
private readonly IDictionary _dictionary;
private readonly object _propertyName;
internal DictionaryPropertyProxy(IDictionary dictionary, string propertyName)
{
_dictionary = dictionary;
// If the given string property matches use it
if (_dictionary.Contains(propertyName))
{
this._propertyName = propertyName;
}
else
{
// Try to find the key by comparing keys as strings
foreach (var dictionaryKey in _dictionary.Keys)
{
if (string.Equals(dictionaryKey.ToString(), propertyName, StringComparison.Ordinal))
{
this._propertyName = dictionaryKey;
break;
}
}
// If existing key was not found,
// store the property name so it can be used for adding
if (this._propertyName == null)
{
this._propertyName = propertyName;
}
}
}
public object? GetValue(object target)
{
if (_dictionary.Contains(_propertyName))
{
return _dictionary[_propertyName];
}
else
{
throw new JsonPatchException(Resources.FormatTargetLocationAtPathSegmentNotFound(_propertyName), null);
}
}
public void SetValue(object target, object? convertedValue)
{
if (_dictionary.Contains(_propertyName))
{
_dictionary[_propertyName] = convertedValue;
}
else
{
_dictionary.Add(_propertyName, convertedValue);
}
}
public void RemoveValue(object target)
{
_dictionary.Remove(_propertyName);
}
public bool CanRead => true;
public bool CanWrite => true;
public Type PropertyType
{
get
{
var val = _dictionary.Contains(_propertyName) ? _dictionary[_propertyName] : null;
if (val == null)
{
return typeof(object);
}
return val.GetType();
}
}
}
}