| | | 1 | | // Licensed to the .NET Foundation under one or more agreements. |
| | | 2 | | // The .NET Foundation licenses this file to you under the MIT license. |
| | | 3 | | |
| | | 4 | | using System.Collections.Generic; |
| | | 5 | | using System.Diagnostics; |
| | | 6 | | using System.Diagnostics.CodeAnalysis; |
| | | 7 | | |
| | | 8 | | namespace System.Text.Json.Nodes |
| | | 9 | | { |
| | | 10 | | /// <summary> |
| | | 11 | | /// Represents a mutable JSON object. |
| | | 12 | | /// </summary> |
| | | 13 | | /// <remarks> |
| | | 14 | | /// It's safe to perform multiple concurrent read operations on a <see cref="JsonObject"/>, |
| | | 15 | | /// but issues can occur if the collection is modified while it's being read. |
| | | 16 | | /// </remarks> |
| | | 17 | | [DebuggerDisplay("JsonObject[{Count}]")] |
| | | 18 | | [DebuggerTypeProxy(typeof(DebugView))] |
| | | 19 | | public sealed partial class JsonObject : JsonNode |
| | | 20 | | { |
| | | 21 | | private JsonElement? _jsonElement; |
| | | 22 | | |
| | 0 | 23 | | internal override JsonElement? UnderlyingElement => _jsonElement; |
| | | 24 | | |
| | | 25 | | /// <summary> |
| | | 26 | | /// Initializes a new instance of the <see cref="JsonObject"/> class that is empty. |
| | | 27 | | /// </summary> |
| | | 28 | | /// <param name="options">Options to control the behavior.</param> |
| | 0 | 29 | | public JsonObject(JsonNodeOptions? options = null) : base(options) { } |
| | | 30 | | |
| | | 31 | | /// <summary> |
| | | 32 | | /// Initializes a new instance of the <see cref="JsonObject"/> class that contains the specified <paramref nam |
| | | 33 | | /// </summary> |
| | | 34 | | /// <param name="properties">The properties to be added.</param> |
| | | 35 | | /// <param name="options">Options to control the behavior.</param> |
| | 0 | 36 | | public JsonObject(IEnumerable<KeyValuePair<string, JsonNode?>> properties, JsonNodeOptions? options = null) : th |
| | 0 | 37 | | { |
| | 0 | 38 | | int capacity = properties is ICollection<KeyValuePair<string, JsonNode?>> propertiesCollection ? propertiesC |
| | 0 | 39 | | OrderedDictionary<string, JsonNode?> dictionary = CreateDictionary(options, capacity); |
| | | 40 | | |
| | 0 | 41 | | foreach (KeyValuePair<string, JsonNode?> node in properties) |
| | 0 | 42 | | { |
| | 0 | 43 | | dictionary.Add(node.Key, node.Value); |
| | 0 | 44 | | node.Value?.AssignParent(this); |
| | 0 | 45 | | } |
| | | 46 | | |
| | 0 | 47 | | _dictionary = dictionary; |
| | 0 | 48 | | } |
| | | 49 | | |
| | | 50 | | /// <summary> |
| | | 51 | | /// Initializes a new instance of the <see cref="JsonObject"/> class that contains properties from the specifi |
| | | 52 | | /// </summary> |
| | | 53 | | /// <returns> |
| | | 54 | | /// The new instance of the <see cref="JsonObject"/> class that contains properties from the specified <see cr |
| | | 55 | | /// </returns> |
| | | 56 | | /// <param name="element">The <see cref="JsonElement"/>.</param> |
| | | 57 | | /// <param name="options">Options to control the behavior.</param> |
| | | 58 | | /// <returns>A <see cref="JsonObject"/>.</returns> |
| | | 59 | | public static JsonObject? Create(JsonElement element, JsonNodeOptions? options = null) |
| | 0 | 60 | | { |
| | 0 | 61 | | return element.ValueKind switch |
| | 0 | 62 | | { |
| | 0 | 63 | | JsonValueKind.Null => null, |
| | 0 | 64 | | JsonValueKind.Object => new JsonObject(element, options), |
| | 0 | 65 | | _ => throw new InvalidOperationException(SR.Format(SR.NodeElementWrongType, nameof(JsonValueKind.Object) |
| | 0 | 66 | | }; |
| | 0 | 67 | | } |
| | | 68 | | |
| | 0 | 69 | | internal JsonObject(JsonElement element, JsonNodeOptions? options = null) : this(options) |
| | 0 | 70 | | { |
| | 0 | 71 | | Debug.Assert(element.ValueKind == JsonValueKind.Object); |
| | 0 | 72 | | _jsonElement = element; |
| | 0 | 73 | | } |
| | | 74 | | |
| | | 75 | | /// <summary> |
| | | 76 | | /// Gets or creates the underlying dictionary containing the properties of the object. |
| | | 77 | | /// </summary> |
| | 0 | 78 | | private OrderedDictionary<string, JsonNode?> Dictionary => _dictionary ?? InitializeDictionary(); |
| | | 79 | | |
| | 0 | 80 | | private protected override JsonNode? GetItem(int index) => GetAt(index).Value; |
| | 0 | 81 | | private protected override void SetItem(int index, JsonNode? value) => SetAt(index, value); |
| | | 82 | | |
| | | 83 | | internal override JsonNode DeepCloneCore() |
| | 0 | 84 | | { |
| | 0 | 85 | | GetUnderlyingRepresentation(out OrderedDictionary<string, JsonNode?>? dictionary, out JsonElement? jsonEleme |
| | | 86 | | |
| | 0 | 87 | | if (dictionary is null) |
| | 0 | 88 | | { |
| | 0 | 89 | | return jsonElement.HasValue |
| | 0 | 90 | | ? new JsonObject(jsonElement.Value.Clone(), Options) |
| | 0 | 91 | | : new JsonObject(Options); |
| | | 92 | | } |
| | | 93 | | |
| | 0 | 94 | | var jObject = new JsonObject(Options) |
| | 0 | 95 | | { |
| | 0 | 96 | | _dictionary = CreateDictionary(Options, Count) |
| | 0 | 97 | | }; |
| | | 98 | | |
| | 0 | 99 | | foreach (KeyValuePair<string, JsonNode?> item in dictionary) |
| | 0 | 100 | | { |
| | 0 | 101 | | jObject.Add(item.Key, item.Value?.DeepCloneCore()); |
| | 0 | 102 | | } |
| | | 103 | | |
| | 0 | 104 | | return jObject; |
| | 0 | 105 | | } |
| | | 106 | | |
| | | 107 | | internal string GetPropertyName(JsonNode? node) |
| | 0 | 108 | | { |
| | 0 | 109 | | KeyValuePair<string, JsonNode?>? item = FindValue(node); |
| | 0 | 110 | | return item.HasValue ? item.Value.Key : string.Empty; |
| | 0 | 111 | | } |
| | | 112 | | |
| | | 113 | | /// <summary> |
| | | 114 | | /// Returns the value of a property with the specified name. |
| | | 115 | | /// </summary> |
| | | 116 | | /// <param name="propertyName">The name of the property to return.</param> |
| | | 117 | | /// <param name="jsonNode">The JSON value of the property with the specified name.</param> |
| | | 118 | | /// <exception cref="ArgumentNullException"> |
| | | 119 | | /// <paramref name="propertyName"/> is <see langword="null"/>. |
| | | 120 | | /// </exception> |
| | | 121 | | /// <returns> |
| | | 122 | | /// <see langword="true"/> if a property with the specified name was found; otherwise, <see langword="false"/> |
| | | 123 | | /// </returns> |
| | 0 | 124 | | public bool TryGetPropertyValue(string propertyName, out JsonNode? jsonNode) => TryGetPropertyValue(propertyName |
| | | 125 | | |
| | | 126 | | /// <summary> |
| | | 127 | | /// Gets the value associated with the specified property name. |
| | | 128 | | /// </summary> |
| | | 129 | | /// <param name="propertyName">The property name of the value to get.</param> |
| | | 130 | | /// <param name="jsonNode"> |
| | | 131 | | /// When this method returns, it contains the value associated with the specified property name, if the proper |
| | | 132 | | /// otherwise <see langword="null"/>. |
| | | 133 | | /// </param> |
| | | 134 | | /// <param name="index">The index of <paramref name="propertyName"/> if found; otherwise, -1.</param> |
| | | 135 | | /// <exception cref="ArgumentNullException"> |
| | | 136 | | /// <paramref name="propertyName"/> is <see langword="null"/>. |
| | | 137 | | /// </exception> |
| | | 138 | | /// <returns> |
| | | 139 | | /// <see langword="true"/> if the <see cref="JsonObject"/> contains an element with the specified property nam |
| | | 140 | | /// </returns> |
| | | 141 | | public bool TryGetPropertyValue(string propertyName, out JsonNode? jsonNode, out int index) |
| | 0 | 142 | | { |
| | 0 | 143 | | ArgumentNullException.ThrowIfNull(propertyName); |
| | | 144 | | |
| | | 145 | | #if NET9_0 |
| | | 146 | | index = Dictionary.IndexOf(propertyName); |
| | | 147 | | if (index < 0) |
| | | 148 | | { |
| | | 149 | | jsonNode = null; |
| | | 150 | | return false; |
| | | 151 | | } |
| | | 152 | | |
| | | 153 | | jsonNode = Dictionary.GetAt(index).Value; |
| | | 154 | | return true; |
| | | 155 | | #else |
| | 0 | 156 | | return Dictionary.TryGetValue(propertyName, out jsonNode, out index); |
| | | 157 | | #endif |
| | 0 | 158 | | } |
| | | 159 | | |
| | | 160 | | /// <inheritdoc/> |
| | | 161 | | public override void WriteTo(Utf8JsonWriter writer, JsonSerializerOptions? options = null) |
| | 0 | 162 | | { |
| | 0 | 163 | | ArgumentNullException.ThrowIfNull(writer); |
| | | 164 | | |
| | 0 | 165 | | GetUnderlyingRepresentation(out OrderedDictionary<string, JsonNode?>? dictionary, out JsonElement? jsonEleme |
| | | 166 | | |
| | 0 | 167 | | if (dictionary is null && jsonElement.HasValue) |
| | 0 | 168 | | { |
| | | 169 | | // Write the element without converting to nodes. |
| | 0 | 170 | | jsonElement.Value.WriteTo(writer); |
| | 0 | 171 | | } |
| | | 172 | | else |
| | 0 | 173 | | { |
| | 0 | 174 | | writer.WriteStartObject(); |
| | 0 | 175 | | WriteContentsTo(writer, options); |
| | 0 | 176 | | writer.WriteEndObject(); |
| | 0 | 177 | | } |
| | 0 | 178 | | } |
| | | 179 | | |
| | | 180 | | /// <summary> |
| | | 181 | | /// Writes the properties of this JsonObject to the writer without the surrounding braces. |
| | | 182 | | /// This is used for extension data serialization where the properties should be flattened |
| | | 183 | | /// into the parent object. |
| | | 184 | | /// </summary> |
| | | 185 | | internal void WriteContentsTo(Utf8JsonWriter writer, JsonSerializerOptions? options) |
| | 0 | 186 | | { |
| | 0 | 187 | | GetUnderlyingRepresentation(out OrderedDictionary<string, JsonNode?>? dictionary, out JsonElement? jsonEleme |
| | | 188 | | |
| | 0 | 189 | | if (dictionary is null && jsonElement.HasValue) |
| | 0 | 190 | | { |
| | | 191 | | // Write properties from the underlying JsonElement without converting to nodes. |
| | 0 | 192 | | foreach (JsonProperty property in jsonElement.Value.EnumerateObject()) |
| | 0 | 193 | | { |
| | 0 | 194 | | property.WriteTo(writer); |
| | 0 | 195 | | } |
| | 0 | 196 | | } |
| | | 197 | | else |
| | 0 | 198 | | { |
| | 0 | 199 | | foreach (KeyValuePair<string, JsonNode?> entry in Dictionary) |
| | 0 | 200 | | { |
| | 0 | 201 | | writer.WritePropertyName(entry.Key); |
| | | 202 | | |
| | 0 | 203 | | if (entry.Value is null) |
| | 0 | 204 | | { |
| | 0 | 205 | | writer.WriteNullValue(); |
| | 0 | 206 | | } |
| | | 207 | | else |
| | 0 | 208 | | { |
| | 0 | 209 | | entry.Value.WriteTo(writer, options); |
| | 0 | 210 | | } |
| | 0 | 211 | | } |
| | 0 | 212 | | } |
| | 0 | 213 | | } |
| | | 214 | | |
| | 0 | 215 | | private protected override JsonValueKind GetValueKindCore() => JsonValueKind.Object; |
| | | 216 | | |
| | | 217 | | internal override bool DeepEqualsCore(JsonNode node) |
| | 0 | 218 | | { |
| | 0 | 219 | | switch (node) |
| | | 220 | | { |
| | | 221 | | case JsonArray: |
| | 0 | 222 | | return false; |
| | | 223 | | case JsonValue value: |
| | | 224 | | // JsonValue instances have special comparison semantics, dispatch to their implementation. |
| | 0 | 225 | | return value.DeepEqualsCore(this); |
| | | 226 | | case JsonObject jsonObject: |
| | 0 | 227 | | OrderedDictionary<string, JsonNode?> currentDict = Dictionary; |
| | 0 | 228 | | OrderedDictionary<string, JsonNode?> otherDict = jsonObject.Dictionary; |
| | | 229 | | |
| | 0 | 230 | | if (currentDict.Count != otherDict.Count) |
| | 0 | 231 | | { |
| | 0 | 232 | | return false; |
| | | 233 | | } |
| | | 234 | | |
| | 0 | 235 | | foreach (KeyValuePair<string, JsonNode?> item in currentDict) |
| | 0 | 236 | | { |
| | 0 | 237 | | if (!otherDict.TryGetValue(item.Key, out JsonNode? jsonNode) || !DeepEquals(item.Value, jsonNode |
| | 0 | 238 | | { |
| | 0 | 239 | | return false; |
| | | 240 | | } |
| | 0 | 241 | | } |
| | | 242 | | |
| | 0 | 243 | | return true; |
| | | 244 | | default: |
| | 0 | 245 | | Debug.Fail("Impossible case"); |
| | | 246 | | return false; |
| | | 247 | | } |
| | 0 | 248 | | } |
| | | 249 | | |
| | | 250 | | internal JsonNode? GetItem(string propertyName) |
| | 0 | 251 | | { |
| | 0 | 252 | | ArgumentNullException.ThrowIfNull(propertyName); |
| | | 253 | | |
| | 0 | 254 | | if (TryGetPropertyValue(propertyName, out JsonNode? value)) |
| | 0 | 255 | | { |
| | 0 | 256 | | return value; |
| | | 257 | | } |
| | | 258 | | |
| | | 259 | | // Return null for missing properties. |
| | 0 | 260 | | return null; |
| | 0 | 261 | | } |
| | | 262 | | |
| | | 263 | | internal override void GetPath(ref ValueStringBuilder path, JsonNode? child) |
| | 0 | 264 | | { |
| | 0 | 265 | | Parent?.GetPath(ref path, this); |
| | | 266 | | |
| | 0 | 267 | | if (child != null) |
| | 0 | 268 | | { |
| | 0 | 269 | | string propertyName = FindValue(child)!.Value.Key; |
| | 0 | 270 | | if (propertyName.AsSpan().ContainsSpecialCharacters()) |
| | 0 | 271 | | { |
| | 0 | 272 | | path.Append("['"); |
| | 0 | 273 | | path.AppendEscapedPropertyName(propertyName); |
| | 0 | 274 | | path.Append("']"); |
| | 0 | 275 | | } |
| | | 276 | | else |
| | 0 | 277 | | { |
| | 0 | 278 | | path.Append('.'); |
| | 0 | 279 | | path.Append(propertyName); |
| | 0 | 280 | | } |
| | 0 | 281 | | } |
| | 0 | 282 | | } |
| | | 283 | | |
| | | 284 | | internal void SetItem(string propertyName, JsonNode? value) |
| | 0 | 285 | | { |
| | 0 | 286 | | ArgumentNullException.ThrowIfNull(propertyName); |
| | | 287 | | |
| | 0 | 288 | | OrderedDictionary<string, JsonNode?> dict = Dictionary; |
| | | 289 | | |
| | 0 | 290 | | if ( |
| | 0 | 291 | | #if NET9_0 |
| | 0 | 292 | | !dict.TryAdd(propertyName, value) |
| | 0 | 293 | | #else |
| | 0 | 294 | | !dict.TryAdd(propertyName, value, out int index) |
| | 0 | 295 | | #endif |
| | 0 | 296 | | ) |
| | 0 | 297 | | { |
| | | 298 | | #if NET9_0 |
| | | 299 | | int index = dict.IndexOf(propertyName); |
| | | 300 | | #endif |
| | 0 | 301 | | Debug.Assert(index >= 0); |
| | 0 | 302 | | JsonNode? replacedValue = dict.GetAt(index).Value; |
| | | 303 | | |
| | 0 | 304 | | if (ReferenceEquals(value, replacedValue)) |
| | 0 | 305 | | { |
| | 0 | 306 | | return; |
| | | 307 | | } |
| | | 308 | | |
| | 0 | 309 | | DetachParent(replacedValue); |
| | 0 | 310 | | dict.SetAt(index, value); |
| | 0 | 311 | | } |
| | | 312 | | |
| | 0 | 313 | | value?.AssignParent(this); |
| | 0 | 314 | | } |
| | | 315 | | |
| | | 316 | | private void DetachParent(JsonNode? item) |
| | 0 | 317 | | { |
| | 0 | 318 | | Debug.Assert(_dictionary != null, "Cannot have detachable nodes without a materialized dictionary."); |
| | | 319 | | |
| | 0 | 320 | | item?.Parent = null; |
| | 0 | 321 | | } |
| | | 322 | | |
| | | 323 | | private KeyValuePair<string, JsonNode?>? FindValue(JsonNode? value) |
| | 0 | 324 | | { |
| | 0 | 325 | | foreach (KeyValuePair<string, JsonNode?> item in Dictionary) |
| | 0 | 326 | | { |
| | 0 | 327 | | if (ReferenceEquals(item.Value, value)) |
| | 0 | 328 | | { |
| | 0 | 329 | | return item; |
| | | 330 | | } |
| | 0 | 331 | | } |
| | | 332 | | |
| | 0 | 333 | | return null; |
| | 0 | 334 | | } |
| | | 335 | | |
| | | 336 | | [ExcludeFromCodeCoverage] // Justification = "Design-time" |
| | | 337 | | private sealed class DebugView |
| | | 338 | | { |
| | | 339 | | [DebuggerBrowsable(DebuggerBrowsableState.Never)] |
| | | 340 | | private readonly JsonObject _node; |
| | | 341 | | |
| | | 342 | | public DebugView(JsonObject node) |
| | | 343 | | { |
| | | 344 | | _node = node; |
| | | 345 | | } |
| | | 346 | | |
| | | 347 | | public string Json => _node.ToJsonString(); |
| | | 348 | | public string Path => _node.GetPath(); |
| | | 349 | | |
| | | 350 | | [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] |
| | | 351 | | private DebugViewProperty[] Items |
| | | 352 | | { |
| | | 353 | | get |
| | | 354 | | { |
| | | 355 | | DebugViewProperty[] properties = new DebugViewProperty[_node.Count]; |
| | | 356 | | |
| | | 357 | | int i = 0; |
| | | 358 | | foreach (KeyValuePair<string, JsonNode?> item in _node) |
| | | 359 | | { |
| | | 360 | | properties[i].PropertyName = item.Key; |
| | | 361 | | properties[i].Value = item.Value; |
| | | 362 | | i++; |
| | | 363 | | } |
| | | 364 | | |
| | | 365 | | return properties; |
| | | 366 | | } |
| | | 367 | | } |
| | | 368 | | |
| | | 369 | | [DebuggerDisplay("{Display,nq}")] |
| | | 370 | | private struct DebugViewProperty |
| | | 371 | | { |
| | | 372 | | [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] |
| | | 373 | | public JsonNode? Value; |
| | | 374 | | |
| | | 375 | | [DebuggerBrowsable(DebuggerBrowsableState.Never)] |
| | | 376 | | public string PropertyName; |
| | | 377 | | |
| | | 378 | | [DebuggerBrowsable(DebuggerBrowsableState.Never)] |
| | | 379 | | public string Display |
| | | 380 | | { |
| | | 381 | | get |
| | | 382 | | { |
| | | 383 | | if (Value == null) |
| | | 384 | | { |
| | | 385 | | return $"{PropertyName} = null"; |
| | | 386 | | } |
| | | 387 | | |
| | | 388 | | if (Value is JsonValue) |
| | | 389 | | { |
| | | 390 | | return $"{PropertyName} = {Value.ToJsonString()}"; |
| | | 391 | | } |
| | | 392 | | |
| | | 393 | | if (Value is JsonObject jsonObject) |
| | | 394 | | { |
| | | 395 | | return $"{PropertyName} = JsonObject[{jsonObject.Count}]"; |
| | | 396 | | } |
| | | 397 | | |
| | | 398 | | JsonArray jsonArray = (JsonArray)Value; |
| | | 399 | | return $"{PropertyName} = JsonArray[{jsonArray.Count}]"; |
| | | 400 | | } |
| | | 401 | | } |
| | | 402 | | |
| | | 403 | | } |
| | | 404 | | } |
| | | 405 | | } |
| | | 406 | | } |