forked from dotnet/runtime
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJsonObject.cs
312 lines (264 loc) · 11.2 KB
/
JsonObject.cs
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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
namespace System.Text.Json.Nodes
{
/// <summary>
/// Represents a mutable JSON object.
/// </summary>
/// <remarks>
/// It's safe to perform multiple concurrent read operations on a <see cref="JsonObject"/>,
/// but issues can occur if the collection is modified while it's being read.
/// </remarks>
[DebuggerDisplay("JsonObject[{Count}]")]
[DebuggerTypeProxy(typeof(DebugView))]
public sealed partial class JsonObject : JsonNode
{
private JsonElement? _jsonElement;
/// <summary>
/// Initializes a new instance of the <see cref="JsonObject"/> class that is empty.
/// </summary>
/// <param name="options">Options to control the behavior.</param>
public JsonObject(JsonNodeOptions? options = null) : base(options) { }
/// <summary>
/// Initializes a new instance of the <see cref="JsonObject"/> class that contains the specified <paramref name="properties"/>.
/// </summary>
/// <param name="properties">The properties to be added.</param>
/// <param name="options">Options to control the behavior.</param>
public JsonObject(IEnumerable<KeyValuePair<string, JsonNode?>> properties, JsonNodeOptions? options = null) : this(options)
{
foreach (KeyValuePair<string, JsonNode?> node in properties)
{
Add(node.Key, node.Value);
}
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonObject"/> class that contains properties from the specified <see cref="JsonElement"/>.
/// </summary>
/// <returns>
/// The new instance of the <see cref="JsonObject"/> class that contains properties from the specified <see cref="JsonElement"/>.
/// </returns>
/// <param name="element">The <see cref="JsonElement"/>.</param>
/// <param name="options">Options to control the behavior.</param>
/// <returns>A <see cref="JsonObject"/>.</returns>
public static JsonObject? Create(JsonElement element, JsonNodeOptions? options = null)
{
return element.ValueKind switch
{
JsonValueKind.Null => null,
JsonValueKind.Object => new JsonObject(element, options),
_ => throw new InvalidOperationException(SR.Format(SR.NodeElementWrongType, nameof(JsonValueKind.Object)))
};
}
internal JsonObject(JsonElement element, JsonNodeOptions? options = null) : this(options)
{
Debug.Assert(element.ValueKind == JsonValueKind.Object);
_jsonElement = element;
}
/// <summary>
/// Gets or creates the underlying dictionary containing the properties of the object.
/// </summary>
internal JsonPropertyDictionary<JsonNode?> Dictionary => _dictionary is { } dictionary ? dictionary : InitializeDictionary();
internal override JsonNode DeepCloneCore()
{
GetUnderlyingRepresentation(out JsonPropertyDictionary<JsonNode?>? dictionary, out JsonElement? jsonElement);
if (dictionary is null)
{
return jsonElement.HasValue
? new JsonObject(jsonElement.Value.Clone(), Options)
: new JsonObject(Options);
}
bool caseInsensitive = Options.HasValue ? Options.Value.PropertyNameCaseInsensitive : false;
var jObject = new JsonObject(Options)
{
_dictionary = new JsonPropertyDictionary<JsonNode?>(caseInsensitive, dictionary.Count)
};
foreach (KeyValuePair<string, JsonNode?> item in dictionary)
{
jObject.Add(item.Key, item.Value?.DeepCloneCore());
}
return jObject;
}
internal string GetPropertyName(JsonNode? node)
{
KeyValuePair<string, JsonNode?>? item = Dictionary.FindValue(node);
return item.HasValue ? item.Value.Key : string.Empty;
}
/// <summary>
/// Returns the value of a property with the specified name.
/// </summary>
/// <param name="propertyName">The name of the property to return.</param>
/// <param name="jsonNode">The JSON value of the property with the specified name.</param>
/// <returns>
/// <see langword="true"/> if a property with the specified name was found; otherwise, <see langword="false"/>.
/// </returns>
public bool TryGetPropertyValue(string propertyName, out JsonNode? jsonNode) =>
((IDictionary<string, JsonNode?>)this).TryGetValue(propertyName, out jsonNode);
/// <inheritdoc/>
public override void WriteTo(Utf8JsonWriter writer, JsonSerializerOptions? options = null)
{
if (writer is null)
{
ThrowHelper.ThrowArgumentNullException(nameof(writer));
}
GetUnderlyingRepresentation(out JsonPropertyDictionary<JsonNode?>? dictionary, out JsonElement? jsonElement);
if (dictionary is null && jsonElement.HasValue)
{
// Write the element without converting to nodes.
jsonElement.Value.WriteTo(writer);
}
else
{
writer.WriteStartObject();
foreach (KeyValuePair<string, JsonNode?> entry in Dictionary)
{
writer.WritePropertyName(entry.Key);
if (entry.Value is null)
{
writer.WriteNullValue();
}
else
{
entry.Value.WriteTo(writer, options);
}
}
writer.WriteEndObject();
}
}
internal override JsonValueKind GetValueKindCore() => JsonValueKind.Object;
internal override bool DeepEqualsCore(JsonNode? node)
{
switch (node)
{
case null or JsonArray:
return false;
case JsonValue value:
// JsonValue instances have special comparison semantics, dispatch to their implementation.
return value.DeepEqualsCore(this);
case JsonObject jsonObject:
JsonPropertyDictionary<JsonNode?> currentDict = Dictionary;
JsonPropertyDictionary<JsonNode?> otherDict = jsonObject.Dictionary;
if (currentDict.Count != otherDict.Count)
{
return false;
}
foreach (KeyValuePair<string, JsonNode?> item in currentDict)
{
JsonNode? jsonNode = otherDict[item.Key];
if (!DeepEquals(item.Value, jsonNode))
{
return false;
}
}
return true;
default:
Debug.Fail("Impossible case");
return false;
}
}
internal JsonNode? GetItem(string propertyName)
{
if (TryGetPropertyValue(propertyName, out JsonNode? value))
{
return value;
}
// Return null for missing properties.
return null;
}
internal override void GetPath(ref ValueStringBuilder path, JsonNode? child)
{
Parent?.GetPath(ref path, this);
if (child != null)
{
string propertyName = Dictionary.FindValue(child)!.Value.Key;
if (propertyName.AsSpan().ContainsSpecialCharacters())
{
path.Append("['");
path.Append(JsonHelpers.GetEscapedPropertyName(propertyName));
path.Append("']");
}
else
{
path.Append('.');
path.Append(propertyName);
}
}
}
internal void SetItem(string propertyName, JsonNode? value)
{
JsonNode? replacedValue = Dictionary.SetValue(propertyName, value, out bool valueAlreadyInDictionary);
if (!valueAlreadyInDictionary)
{
value?.AssignParent(this);
}
DetachParent(replacedValue);
}
private void DetachParent(JsonNode? item)
{
Debug.Assert(_dictionary != null, "Cannot have detachable nodes without a materialized dictionary.");
if (item != null)
{
item.Parent = null;
}
}
[ExcludeFromCodeCoverage] // Justification = "Design-time"
private sealed class DebugView
{
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private readonly JsonObject _node;
public DebugView(JsonObject node)
{
_node = node;
}
public string Json => _node.ToJsonString();
public string Path => _node.GetPath();
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
private DebugViewProperty[] Items
{
get
{
DebugViewProperty[] properties = new DebugViewProperty[_node.Count];
int i = 0;
foreach (KeyValuePair<string, JsonNode?> item in _node)
{
properties[i].PropertyName = item.Key;
properties[i].Value = item.Value;
i++;
}
return properties;
}
}
[DebuggerDisplay("{Display,nq}")]
private struct DebugViewProperty
{
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public JsonNode? Value;
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public string PropertyName;
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public string Display
{
get
{
if (Value == null)
{
return $"{PropertyName} = null";
}
if (Value is JsonValue)
{
return $"{PropertyName} = {Value.ToJsonString()}";
}
if (Value is JsonObject jsonObject)
{
return $"{PropertyName} = JsonObject[{jsonObject.Count}]";
}
JsonArray jsonArray = (JsonArray)Value;
return $"{PropertyName} = JsonArray[{jsonArray.Count}]";
}
}
}
}
}
}