-
Notifications
You must be signed in to change notification settings - Fork 5.5k
Expand file tree
/
Copy pathJsonNode.cs
More file actions
384 lines (336 loc) · 13.1 KB
/
Copy pathJsonNode.cs
File metadata and controls
384 lines (336 loc) · 13.1 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
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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
// 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.CodeAnalysis;
using System.Text.Json.Serialization.Converters;
using System.Text.Json.Serialization.Metadata;
namespace System.Text.Json.Nodes
{
/// <summary>
/// The base class that represents a single node within a mutable JSON document.
/// </summary>
/// <seealso cref="JsonSerializerOptions.UnknownTypeHandling"/> to specify that a type
/// declared as an <see cref="object"/> should be deserialized as a <see cref="JsonNode"/>.
public abstract partial class JsonNode
{
private JsonNode? _parent;
private JsonNodeOptions? _options;
/// <summary>
/// Options to control the behavior.
/// </summary>
public JsonNodeOptions? Options
{
get
{
if (!_options.HasValue && Parent != null)
{
// Remember the parent options; if node is re-parented later we still want to keep the
// original options since they may have affected the way the node was created as is the case
// with JsonObject's case-insensitive dictionary.
_options = Parent.Options;
}
return _options;
}
}
internal JsonNode(JsonNodeOptions? options = null)
{
_options = options;
}
/// <summary>
/// Casts to the derived <see cref="JsonArray"/> type.
/// </summary>
/// <returns>
/// A <see cref="JsonArray"/>.
/// </returns>
/// <exception cref="InvalidOperationException">
/// The node is not a <see cref="JsonArray"/>.
/// </exception>
public JsonArray AsArray()
{
JsonArray? jArray = this as JsonArray;
if (jArray is null)
{
ThrowHelper.ThrowInvalidOperationException_NodeWrongType(nameof(JsonArray));
}
return jArray;
}
/// <summary>
/// Casts to the derived <see cref="JsonObject"/> type.
/// </summary>
/// <returns>
/// A <see cref="JsonObject"/>.
/// </returns>
/// <exception cref="InvalidOperationException">
/// The node is not a <see cref="JsonObject"/>.
/// </exception>
public JsonObject AsObject()
{
JsonObject? jObject = this as JsonObject;
if (jObject is null)
{
ThrowHelper.ThrowInvalidOperationException_NodeWrongType(nameof(JsonObject));
}
return jObject;
}
/// <summary>
/// Casts to the derived <see cref="JsonValue"/> type.
/// </summary>
/// <returns>
/// A <see cref="JsonValue"/>.
/// </returns>
/// <exception cref="InvalidOperationException">
/// The node is not a <see cref="JsonValue"/>.
/// </exception>
public JsonValue AsValue()
{
JsonValue? jValue = this as JsonValue;
if (jValue is null)
{
ThrowHelper.ThrowInvalidOperationException_NodeWrongType(nameof(JsonValue));
}
return jValue;
}
/// <summary>
/// Gets the parent <see cref="JsonNode"/>.
/// If there is no parent, <see langword="null"/> is returned.
/// A parent can either be a <see cref="JsonObject"/> or a <see cref="JsonArray"/>.
/// </summary>
public JsonNode? Parent
{
get
{
return _parent;
}
internal set
{
_parent = value;
}
}
/// <summary>
/// Gets the JSON path.
/// </summary>
/// <returns>The JSON Path value.</returns>
public string GetPath()
{
if (Parent == null)
{
return "$";
}
var path = new List<string>();
GetPath(path, null);
var sb = new StringBuilder("$");
for (int i = path.Count - 1; i >= 0; i--)
{
sb.Append(path[i]);
}
return sb.ToString();
}
internal abstract void GetPath(List<string> path, JsonNode? child);
/// <summary>
/// Gets the root <see cref="JsonNode"/>.
/// </summary>
/// <remarks>
/// The current node is returned if it is a root.
/// </remarks>
public JsonNode Root
{
get
{
JsonNode? parent = Parent;
if (parent == null)
{
return this;
}
while (parent.Parent != null)
{
parent = parent.Parent;
}
return parent;
}
}
/// <summary>
/// Gets the value for the current <see cref="JsonValue"/>.
/// </summary>
/// <typeparam name="T">The type of the value to obtain from the <see cref="JsonValue"/>.</typeparam>
/// <returns>A value converted from the <see cref="JsonValue"/> instance.</returns>
/// <remarks>
/// {T} can be the type or base type of the underlying value.
/// If the underlying value is a <see cref="JsonElement"/> then {T} can also be the type of any primitive
/// value supported by current <see cref="JsonElement"/>.
/// Specifying the <see cref="object"/> type for {T} will always succeed and return the underlying value as <see cref="object"/>.<br />
/// The underlying value of a <see cref="JsonValue"/> after deserialization is an instance of <see cref="JsonElement"/>,
/// otherwise it's the value specified when the <see cref="JsonValue"/> was created.
/// </remarks>
/// <seealso cref="System.Text.Json.Nodes.JsonValue.TryGetValue"></seealso>
/// <exception cref="FormatException">
/// The current <see cref="JsonNode"/> cannot be represented as a {T}.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The current <see cref="JsonNode"/> is not a <see cref="JsonValue"/> or
/// is not compatible with {T}.
/// </exception>
public virtual T GetValue<T>() =>
throw new InvalidOperationException(SR.Format(SR.NodeWrongType, nameof(JsonValue)));
/// <summary>
/// Gets or sets the element at the specified index.
/// </summary>
/// <param name="index">The zero-based index of the element to get or set.</param>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="index"/> is less than 0 or <paramref name="index"/> is greater than the number of properties.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The current <see cref="JsonNode"/> is not a <see cref="JsonArray"/>.
/// </exception>
public JsonNode? this[int index]
{
get
{
return AsArray().GetItem(index);
}
set
{
AsArray().SetItem(index, value);
}
}
/// <summary>
/// Gets or sets the element with the specified property name.
/// If the property is not found, <see langword="null"/> is returned.
/// </summary>
/// <param name="propertyName">The name of the property to return.</param>
/// <exception cref="ArgumentNullException">
/// <paramref name="propertyName"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The current <see cref="JsonNode"/> is not a <see cref="JsonObject"/>.
/// </exception>
public JsonNode? this[string propertyName]
{
get
{
return AsObject().GetItem(propertyName);
}
set
{
AsObject().SetItem(propertyName, value);
}
}
/// <summary>
/// Creates a new instance of the <see cref="JsonNode"/>. All children nodes are recursively cloned.
/// </summary>
public JsonNode DeepClone() => DeepCloneCore();
internal abstract JsonNode DeepCloneCore();
/// <summary>
/// Returns <see cref="JsonValueKind"/> of current instance.
/// </summary>
public JsonValueKind GetValueKind() => GetValueKindCore();
internal abstract JsonValueKind GetValueKindCore();
/// <summary>
/// Returns property name of the current node from the parent object.
/// </summary>
/// <exception cref="InvalidOperationException">
/// The current parent is not a <see cref="JsonObject"/>.
/// </exception>
public string GetPropertyName()
{
JsonObject? parentObject = _parent as JsonObject;
if (parentObject is null)
{
ThrowHelper.ThrowInvalidOperationException_NodeParentWrongType(nameof(JsonObject));
}
return parentObject.GetPropertyName(this);
}
/// <summary>
/// Returns index of the current node from the parent <see cref="JsonArray" />.
/// </summary>
/// <exception cref="InvalidOperationException">
/// The current parent is not a <see cref="JsonArray"/>.
/// </exception>
public int GetElementIndex()
{
JsonArray? parentArray = _parent as JsonArray;
if (parentArray is null)
{
ThrowHelper.ThrowInvalidOperationException_NodeParentWrongType(nameof(JsonArray));
}
return parentArray.GetElementIndex(this);
}
/// <summary>
/// Compares the values of two nodes, including the values of all descendant nodes.
/// </summary>
/// <param name="node1">The <see cref="JsonNode"/> to compare.</param>
/// <param name="node2">The <see cref="JsonNode"/> to compare.</param>
/// <returns><c>true</c> if the tokens are equal; otherwise <c>false</c>.</returns>
public static bool DeepEquals(JsonNode? node1, JsonNode? node2)
{
if (node1 is null)
{
return node2 is null;
}
return node1.DeepEqualsCore(node2);
}
internal abstract bool DeepEqualsCore(JsonNode? node);
/// <summary>
/// Replaces this node with a new value.
/// </summary>
/// <typeparam name="T">The type of value to be replaced.</typeparam>
/// <param name="value">Value that replaces this node.</param>
[RequiresUnreferencedCode(JsonValue.CreateUnreferencedCodeMessage)]
[RequiresDynamicCode(JsonValue.CreateDynamicCodeMessage)]
public void ReplaceWith<T>(T value)
{
JsonNode? node;
switch (_parent)
{
case JsonObject jsonObject:
node = ConvertFromValue(value);
jsonObject.SetItem(GetPropertyName(), node);
return;
case JsonArray jsonArray:
node = ConvertFromValue(value);
jsonArray.SetItem(GetElementIndex(), node);
return;
}
}
internal void AssignParent(JsonNode parent)
{
if (Parent != null)
{
ThrowHelper.ThrowInvalidOperationException_NodeAlreadyHasParent();
}
JsonNode? p = parent;
while (p != null)
{
if (p == this)
{
ThrowHelper.ThrowInvalidOperationException_NodeCycleDetected();
}
p = p.Parent;
}
Parent = parent;
}
/// <summary>
/// Adaptation of the equivalent JsonValue.Create factory method extended
/// to support arbitrary <see cref="JsonElement"/> and <see cref="JsonNode"/> values.
/// TODO consider making public cf. https://github.com/dotnet/runtime/issues/70427
/// </summary>
[RequiresUnreferencedCode(JsonSerializer.SerializationUnreferencedCodeMessage)]
[RequiresDynamicCode(JsonSerializer.SerializationRequiresDynamicCodeMessage)]
internal static JsonNode? ConvertFromValue<T>(T? value, JsonNodeOptions? options = null)
{
if (value is null)
{
return null;
}
if (value is JsonNode node)
{
return node;
}
if (value is JsonElement element)
{
return JsonNodeConverter.Create(element, options);
}
var jsonTypeInfo = (JsonTypeInfo<T>)JsonSerializerOptions.Default.GetTypeInfo(typeof(T));
return new JsonValueCustomized<T>(value, jsonTypeInfo, options);
}
}
}