diff --git a/src/System.Text.Json/docs/writable_json_dom_spec.md b/src/System.Text.Json/docs/writable_json_dom_spec.md
index 8a3288a3456c..9e033ea1413c 100644
--- a/src/System.Text.Json/docs/writable_json_dom_spec.md
+++ b/src/System.Text.Json/docs/writable_json_dom_spec.md
@@ -243,6 +243,7 @@ Mailbox.SendAllEmployeesData(employees.AsJsonElement());
* Do we want to add recursive equals on `JsonArray` and `JsonObject`?
* Do we want to make `JsonNode` derived types implement `IComparable` (which ones)?
* Do we want `JsonObject` to implement `IDictionary` and `JsonArray` to implement `IList` (currently JsonArray does, but JsonObject not)?
+* Do we want `JsonArray` to support `Contains`, `IndexOf` and `LastIndexOf` if we keep reference equality for `JsonArray`/`JsonObject` and don't have a good way of comparing numbers?
* Would escaped characters be supported for creating `JsonNumber` from string?
* Is the API for `JsonNode` and `JsonElement` interactions sufficient?
* Do we want to support duplicate and order preservation/control when adding/removing values in `JsonArray`/`JsonObject`?
@@ -251,7 +252,7 @@ Mailbox.SendAllEmployeesData(employees.AsJsonElement());
| Solution | Pros | Cons |
|----------|:-------------|--------|
|current API| - no additional checks need to be made | - creating recursive loop by the user may be problematic |
- |tracking nodes | - handles recursive loop problem | - when node is added to a parent, it needs to be checked if it already has a parent and make a copy if it has |
+ |tracking nodes | - handles recursive loop problem | - when node is added to a parent, it needs to be checked if it already has a parent and make a copy if it has |
* Do we want to change `JsonNumber`'s backing field to something different than `string`?
Suggestions:
- `Span` or array of `Utf8String`/`Char8` (once they come online in the future) / `byte`
@@ -262,7 +263,12 @@ Mailbox.SendAllEmployeesData(employees.AsJsonElement());
* Should `ToString` on `JsonBoolean` and `JsonString` return the .NET or JSON representation?
* Do we want to keep implicit cast operators (even though for `JsonNumber` it would mean throwing in some cases, which is against FDG)?
* Do we want overloads that take a `StringComparison` enum for methods retrieving properties? It would make API easier to use where case is not important.
-* Where do we want to enable user to set handling properties manner?
+* Where do we want to enable user to set handling properties manner? Do we want to support it as `JsonElement` does not?
+* Do we want to support transforming `JsonObject` into JSON string? Should `ToString` behave this way or do we want an additional method - e.g. `GetJsonString` (it might be confusing as we have a type `JsonString`) or `GetJsonRepresenation`?
+* `AsJsonElement` function on `JsonNode` currently does not work for `null` node. Do we want to support null case somehow?
+* Do we want both `Clone` and `DeepCopy` methods for `JsonNode`?
+* Are we OK with needing to cast `JsonArray` to `JsonNode` in order to add it to `JsonObject`? (there's an ambiguous call between `JsonArray` and `IEnumerable` right now)
+* Do we want `IsImmutable` property for `JsonElement`?
## Useful links
diff --git a/src/System.Text.Json/ref/System.Text.Json.cs b/src/System.Text.Json/ref/System.Text.Json.cs
index d39590d2a7a0..262999f99056 100644
--- a/src/System.Text.Json/ref/System.Text.Json.cs
+++ b/src/System.Text.Json/ref/System.Text.Json.cs
@@ -13,11 +13,97 @@ public enum DuplicatePropertyNameHandling
Ignore = 1,
Error = 2,
}
+ public sealed partial class JsonArray : System.Text.Json.JsonNode, System.Collections.Generic.ICollection, System.Collections.Generic.IEnumerable, System.Collections.Generic.IList, System.Collections.Generic.IReadOnlyCollection, System.Collections.Generic.IReadOnlyList, System.Collections.IEnumerable
+ {
+ public JsonArray() { }
+ public JsonArray(System.Collections.Generic.IEnumerable values) { }
+ public JsonArray(System.Collections.Generic.IEnumerable values) { }
+ public JsonArray(System.Collections.Generic.IEnumerable values) { }
+ public JsonArray(System.Collections.Generic.IEnumerable values) { }
+ public JsonArray(System.Collections.Generic.IEnumerable values) { }
+ public JsonArray(System.Collections.Generic.IEnumerable values) { }
+ public JsonArray(System.Collections.Generic.IEnumerable values) { }
+ [System.CLSCompliantAttribute(false)]
+ public JsonArray(System.Collections.Generic.IEnumerable values) { }
+ public JsonArray(System.Collections.Generic.IEnumerable values) { }
+ public JsonArray(System.Collections.Generic.IEnumerable values) { }
+ public JsonArray(System.Collections.Generic.IEnumerable values) { }
+ [System.CLSCompliantAttribute(false)]
+ public JsonArray(System.Collections.Generic.IEnumerable values) { }
+ [System.CLSCompliantAttribute(false)]
+ public JsonArray(System.Collections.Generic.IEnumerable values) { }
+ [System.CLSCompliantAttribute(false)]
+ public JsonArray(System.Collections.Generic.IEnumerable values) { }
+ public int Count { get { throw null; } }
+ public bool IsReadOnly { get { throw null; } }
+ public System.Text.Json.JsonNode this[int idx] { get { throw null; } set { } }
+ public override System.Text.Json.JsonValueKind ValueKind { get { throw null; } }
+ public void Add(bool value) { }
+ public void Add(byte value) { }
+ public void Add(decimal value) { }
+ public void Add(double value) { }
+ public void Add(short value) { }
+ public void Add(int value) { }
+ public void Add(long value) { }
+ [System.CLSCompliantAttribute(false)]
+ public void Add(sbyte value) { }
+ public void Add(float value) { }
+ public void Add(string value) { }
+ public void Add(System.Text.Json.JsonNode value) { }
+ [System.CLSCompliantAttribute(false)]
+ public void Add(ushort value) { }
+ [System.CLSCompliantAttribute(false)]
+ public void Add(uint value) { }
+ [System.CLSCompliantAttribute(false)]
+ public void Add(ulong value) { }
+ public void Clear() { }
+ public override System.Text.Json.JsonNode Clone() { throw null; }
+ public bool Contains(System.Text.Json.JsonNode value) { throw null; }
+ public System.Text.Json.JsonArrayEnumerator GetEnumerator() { throw null; }
+ public int IndexOf(System.Text.Json.JsonNode item) { throw null; }
+ public void Insert(int index, bool item) { }
+ public void Insert(int index, byte item) { }
+ public void Insert(int index, decimal item) { }
+ public void Insert(int index, double item) { }
+ public void Insert(int index, short item) { }
+ public void Insert(int index, int item) { }
+ public void Insert(int index, long item) { }
+ [System.CLSCompliantAttribute(false)]
+ public void Insert(int index, sbyte item) { }
+ public void Insert(int index, float item) { }
+ public void Insert(int index, string item) { }
+ public void Insert(int index, System.Text.Json.JsonNode item) { }
+ [System.CLSCompliantAttribute(false)]
+ public void Insert(int index, ushort item) { }
+ [System.CLSCompliantAttribute(false)]
+ public void Insert(int index, uint item) { }
+ [System.CLSCompliantAttribute(false)]
+ public void Insert(int index, ulong item) { }
+ public int LastIndexOf(System.Text.Json.JsonNode item) { throw null; }
+ public bool Remove(System.Text.Json.JsonNode item) { throw null; }
+ public int RemoveAll(System.Predicate match) { throw null; }
+ public void RemoveAt(int index) { }
+ void System.Collections.Generic.ICollection.CopyTo(System.Text.Json.JsonNode[] array, int arrayIndex) { }
+ System.Collections.Generic.IEnumerator System.Collections.Generic.IEnumerable.GetEnumerator() { throw null; }
+ System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
+ }
+ public partial struct JsonArrayEnumerator : System.Collections.Generic.IEnumerator, System.Collections.IEnumerator, System.IDisposable
+ {
+ private object _dummy;
+ public JsonArrayEnumerator(System.Text.Json.JsonArray jsonArray) { throw null; }
+ public System.Text.Json.JsonNode Current { get { throw null; } }
+ object System.Collections.IEnumerator.Current { get { throw null; } }
+ public void Dispose() { }
+ public bool MoveNext() { throw null; }
+ void System.Collections.IEnumerator.Reset() { }
+ }
public sealed partial class JsonBoolean : System.Text.Json.JsonNode, System.IEquatable
{
public JsonBoolean() { }
public JsonBoolean(bool value) { }
public bool Value { get { throw null; } set { } }
+ public override System.Text.Json.JsonValueKind ValueKind { get { throw null; } }
+ public override System.Text.Json.JsonNode Clone() { throw null; }
public override bool Equals(object obj) { throw null; }
public bool Equals(System.Text.Json.JsonBoolean other) { throw null; }
public override int GetHashCode() { throw null; }
@@ -58,6 +144,7 @@ public readonly partial struct JsonElement
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
+ public bool IsImmutable { get { throw null; } }
public System.Text.Json.JsonElement this[int index] { get { throw null; } }
public System.Text.Json.JsonValueKind ValueKind { get { throw null; } }
public System.Text.Json.JsonElement Clone() { throw null; }
@@ -178,6 +265,13 @@ protected JsonNamingPolicy() { }
public abstract partial class JsonNode
{
internal JsonNode() { }
+ public abstract System.Text.Json.JsonValueKind ValueKind { get; }
+ public System.Text.Json.JsonElement AsJsonElement() { throw null; }
+ public abstract System.Text.Json.JsonNode Clone();
+ public static System.Text.Json.JsonNode DeepCopy(System.Text.Json.JsonElement jsonElement) { throw null; }
+ public static System.Text.Json.JsonNode GetNode(System.Text.Json.JsonElement jsonElement) { throw null; }
+ public static System.Text.Json.JsonNode Parse(string json) { throw null; }
+ public static bool TryGetNode(System.Text.Json.JsonElement jsonElement, out System.Text.Json.JsonNode jsonNode) { throw null; }
}
public sealed partial class JsonNumber : System.Text.Json.JsonNode, System.IEquatable
{
@@ -198,6 +292,8 @@ public JsonNumber(ushort value) { }
public JsonNumber(uint value) { }
[System.CLSCompliantAttribute(false)]
public JsonNumber(ulong value) { }
+ public override System.Text.Json.JsonValueKind ValueKind { get { throw null; } }
+ public override System.Text.Json.JsonNode Clone() { throw null; }
public override bool Equals(object obj) { throw null; }
public bool Equals(System.Text.Json.JsonNumber other) { throw null; }
public byte GetByte() { throw null; }
@@ -273,9 +369,11 @@ public JsonObject(System.Text.Json.DuplicatePropertyNameHandling duplicateProper
public System.Text.Json.JsonNode this[string propertyName] { get { throw null; } set { } }
public System.Collections.Generic.ICollection PropertyNames { get { throw null; } }
public System.Collections.Generic.ICollection PropertyValues { get { throw null; } }
+ public override System.Text.Json.JsonValueKind ValueKind { get { throw null; } }
public void Add(System.Collections.Generic.KeyValuePair jsonProperty) { }
public void Add(string propertyName, bool propertyValue) { }
public void Add(string propertyName, byte propertyValue) { }
+ public void Add(string propertyName, System.Collections.Generic.IEnumerable propertyValues) { }
public void Add(string propertyName, System.DateTime propertyValue) { }
public void Add(string propertyName, System.DateTimeOffset propertyValue) { }
public void Add(string propertyName, decimal propertyValue) { }
@@ -297,12 +395,16 @@ public void Add(string propertyName, uint propertyValue) { }
[System.CLSCompliantAttribute(false)]
public void Add(string propertyName, ulong propertyValue) { }
public void AddRange(System.Collections.Generic.IEnumerable> jsonProperties) { }
+ public override System.Text.Json.JsonNode Clone() { throw null; }
public bool ContainsProperty(string propertyName) { throw null; }
- public System.Collections.Generic.IEnumerator> GetEnumerator() { throw null; }
+ public System.Text.Json.JsonObjectEnumerator GetEnumerator() { throw null; }
+ public System.Text.Json.JsonArray GetJsonArrayPropertyValue(string propertyName) { throw null; }
public System.Text.Json.JsonObject GetJsonObjectPropertyValue(string propertyName) { throw null; }
public System.Text.Json.JsonNode GetPropertyValue(string propertyName) { throw null; }
public bool Remove(string propertyName) { throw null; }
+ System.Collections.Generic.IEnumerator> System.Collections.Generic.IEnumerable>.GetEnumerator() { throw null; }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
+ public bool TryGetJsonArrayPropertyValue(string propertyName, out System.Text.Json.JsonArray jsonArray) { throw null; }
public bool TryGetJsonObjectPropertyValue(string propertyName, out System.Text.Json.JsonObject jsonObject) { throw null; }
public bool TryGetPropertyValue(string propertyName, out System.Text.Json.JsonNode jsonNode) { throw null; }
}
@@ -314,7 +416,7 @@ public partial struct JsonObjectEnumerator : System.Collections.Generic.IEnumera
object System.Collections.IEnumerator.Current { get { throw null; } }
public void Dispose() { }
public bool MoveNext() { throw null; }
- public void Reset() { }
+ void System.Collections.IEnumerator.Reset() { }
}
public readonly partial struct JsonProperty
{
@@ -386,13 +488,21 @@ public JsonString(System.Guid value) { }
public JsonString(System.ReadOnlySpan value) { }
public JsonString(string value) { }
public string Value { get { throw null; } set { } }
+ public override System.Text.Json.JsonValueKind ValueKind { get { throw null; } }
+ public override System.Text.Json.JsonNode Clone() { throw null; }
public override bool Equals(object obj) { throw null; }
public bool Equals(System.Text.Json.JsonString other) { throw null; }
+ public System.DateTime GetDateTime() { throw null; }
+ public System.DateTimeOffset GetDateTimeOffset() { throw null; }
+ public System.Guid GetGuid() { throw null; }
public override int GetHashCode() { throw null; }
public static bool operator ==(System.Text.Json.JsonString left, System.Text.Json.JsonString right) { throw null; }
public static implicit operator System.Text.Json.JsonString (string value) { throw null; }
public static bool operator !=(System.Text.Json.JsonString left, System.Text.Json.JsonString right) { throw null; }
public override string ToString() { throw null; }
+ public bool TryGetDateTime(out System.DateTime value) { throw null; }
+ public bool TryGetDateTimeOffset(out System.DateTimeOffset value) { throw null; }
+ public bool TryGetGuid(out System.Guid value) { throw null; }
}
public enum JsonTokenType : byte
{
diff --git a/src/System.Text.Json/src/Resources/Strings.resx b/src/System.Text.Json/src/Resources/Strings.resx
index 0b044d0effe1..88921151ae62 100644
--- a/src/System.Text.Json/src/Resources/Strings.resx
+++ b/src/System.Text.Json/src/Resources/Strings.resx
@@ -441,4 +441,7 @@
The DuplicatePropertyNameHandling enum must be set to one of the supported values.
+
+ The JSON array was modified during iteration.
+
\ No newline at end of file
diff --git a/src/System.Text.Json/src/System.Text.Json.csproj b/src/System.Text.Json/src/System.Text.Json.csproj
index bbbae86a515b..3e2278e2decc 100644
--- a/src/System.Text.Json/src/System.Text.Json.csproj
+++ b/src/System.Text.Json/src/System.Text.Json.csproj
@@ -211,6 +211,8 @@
+
+
diff --git a/src/System.Text.Json/src/System/Text/Json/Document/JsonElement.ArrayEnumerator.cs b/src/System.Text.Json/src/System/Text/Json/Document/JsonElement.ArrayEnumerator.cs
index 2362bddc1d2e..34edd8cd3853 100644
--- a/src/System.Text.Json/src/System/Text/Json/Document/JsonElement.ArrayEnumerator.cs
+++ b/src/System.Text.Json/src/System/Text/Json/Document/JsonElement.ArrayEnumerator.cs
@@ -18,20 +18,51 @@ public struct ArrayEnumerator : IEnumerable, IEnumerator
- public JsonElement Current =>
- _curIdx < 0 ? default : new JsonElement(_target._parent, _curIdx);
+ public JsonElement Current
+ {
+ get
+ {
+ if (_curIdx < 0)
+ {
+ return default;
+ }
+
+ if (_target._parent is JsonArray jsonArray)
+ {
+ if (_curIdx >= jsonArray.Count)
+ {
+ return default;
+ }
+
+ return jsonArray[_curIdx].AsJsonElement();
+ }
+
+ var document = (JsonDocument)_target._parent;
+ return new JsonElement(document, _curIdx);
+ }
+ }
///
/// Returns an enumerator that iterates through a collection.
@@ -56,7 +87,7 @@ public ArrayEnumerator GetEnumerator()
///
public void Dispose()
{
- _curIdx = _endIdx;
+ _curIdx = _endIdxOrVersion;
}
///
@@ -71,7 +102,23 @@ public void Reset()
///
public bool MoveNext()
{
- if (_curIdx >= _endIdx)
+ if (_target._parent is JsonArray jsonArray)
+ {
+ if (jsonArray._version != _endIdxOrVersion)
+ {
+ throw new InvalidOperationException(SR.ArrayModifiedDuringIteration);
+ }
+
+ if (_curIdx >= jsonArray.Count)
+ {
+ return false;
+ }
+
+ _curIdx++;
+ return _curIdx < jsonArray.Count;
+ }
+
+ if (_curIdx >= _endIdxOrVersion)
{
return false;
}
@@ -82,10 +129,11 @@ public bool MoveNext()
}
else
{
- _curIdx = _target._parent.GetEndIndex(_curIdx, includeEndElement: true);
+ var document = (JsonDocument)_target._parent;
+ _curIdx = document.GetEndIndex(_curIdx, includeEndElement: true);
}
- return _curIdx < _endIdx;
+ return _curIdx < _endIdxOrVersion;
}
}
}
diff --git a/src/System.Text.Json/src/System/Text/Json/Document/JsonElement.ObjectEnumerator.cs b/src/System.Text.Json/src/System/Text/Json/Document/JsonElement.ObjectEnumerator.cs
index 2b2b40a99b3e..92968bacb1f0 100644
--- a/src/System.Text.Json/src/System/Text/Json/Document/JsonElement.ObjectEnumerator.cs
+++ b/src/System.Text.Json/src/System/Text/Json/Document/JsonElement.ObjectEnumerator.cs
@@ -19,21 +19,62 @@ public struct ObjectEnumerator : IEnumerable, IEnumerator
- public JsonProperty Current =>
- _curIdx < 0 ?
- default :
- new JsonProperty(new JsonElement(_target._parent, _curIdx));
+ public JsonProperty Current
+ {
+ get
+ {
+ if (!_target.IsImmutable)
+ {
+ KeyValuePair propertyPair = _jsonObjectEnumerator.Current;
+
+ // propertyPair.Key is null before first after last call of MoveNext
+ if (propertyPair.Key == null)
+ {
+ return default;
+ }
+
+ // null JsonNode case
+ if (propertyPair.Value == null)
+ {
+ return new JsonProperty(new JsonElement(null), propertyPair.Key);
+ }
+
+ return new JsonProperty(propertyPair.Value.AsJsonElement(), propertyPair.Key);
+ }
+
+ if (_curIdx < 0)
+ {
+ return default;
+ }
+
+ var document = (JsonDocument)_target._parent;
+ return new JsonProperty(new JsonElement(document, _curIdx));
+ }
+ }
///
/// Returns an enumerator that iterates the properties of an object.
@@ -65,12 +106,20 @@ public ObjectEnumerator GetEnumerator()
public void Dispose()
{
_curIdx = _endIdx;
+ if (!_target.IsImmutable)
+ {
+ _jsonObjectEnumerator.Dispose();
+ }
}
///
public void Reset()
{
_curIdx = -1;
+ if (!_target.IsImmutable)
+ {
+ ((IEnumerator)_jsonObjectEnumerator).Reset();
+ }
}
///
@@ -79,6 +128,11 @@ public void Reset()
///
public bool MoveNext()
{
+ if (!_target.IsImmutable)
+ {
+ return _jsonObjectEnumerator.MoveNext();
+ }
+
if (_curIdx >= _endIdx)
{
return false;
@@ -90,7 +144,8 @@ public bool MoveNext()
}
else
{
- _curIdx = _target._parent.GetEndIndex(_curIdx, includeEndElement: true);
+ var document = (JsonDocument)_target._parent;
+ _curIdx = document.GetEndIndex(_curIdx, includeEndElement: true);
}
// _curIdx is now pointing at a property name, move one more to get the value
diff --git a/src/System.Text.Json/src/System/Text/Json/Document/JsonElement.cs b/src/System.Text.Json/src/System/Text/Json/Document/JsonElement.cs
index 9fa492d5c23d..94bf57923d46 100644
--- a/src/System.Text.Json/src/System/Text/Json/Document/JsonElement.cs
+++ b/src/System.Text.Json/src/System/Text/Json/Document/JsonElement.cs
@@ -13,7 +13,7 @@ namespace System.Text.Json
[DebuggerDisplay("{DebuggerDisplay,nq}")]
public readonly partial struct JsonElement
{
- private readonly JsonDocument _parent;
+ internal readonly object _parent;
private readonly int _idx;
internal JsonElement(JsonDocument parent, int idx)
@@ -27,15 +27,51 @@ internal JsonElement(JsonDocument parent, int idx)
_idx = idx;
}
- private JsonTokenType TokenType => _parent?.GetJsonTokenType(_idx) ?? JsonTokenType.None;
+ internal JsonElement(JsonNode parent)
+ {
+ _parent = parent;
+ _idx = -1;
+ }
+
+ ///
+ /// Indicates whether or not this instance is immutable.
+ ///
+ public bool IsImmutable => _idx != -1;
+ [DebuggerBrowsable(DebuggerBrowsableState.Never)]
+ private JsonTokenType TokenType
+ {
+ get
+ {
+ JsonDocument document = (JsonDocument)_parent;
+ return document?.GetJsonTokenType(_idx) ?? JsonTokenType.None;
+ }
+ }
///
/// The that the value is.
///
///
/// The parent has been disposed.
///
- public JsonValueKind ValueKind => TokenType.ToValueKind();
+ public JsonValueKind ValueKind
+ {
+ get
+ {
+ if (IsImmutable)
+ {
+ return TokenType.ToValueKind();
+ }
+
+ var jsonNode = (JsonNode)_parent;
+
+ if (jsonNode == null)
+ {
+ return JsonValueKind.Null;
+ }
+
+ return jsonNode.ValueKind;
+ }
+ }
///
/// Get the value at a specified index when the current value is a
@@ -56,7 +92,19 @@ public JsonElement this[int index]
{
CheckValidInstance();
- return _parent.GetArrayIndexElement(_idx, index);
+ if (_parent is JsonDocument document)
+ {
+ return document.GetArrayIndexElement(_idx, index);
+ }
+
+ var jsonNode = (JsonNode)_parent;
+
+ if (jsonNode is JsonArray jsonArray)
+ {
+ return jsonArray[index].AsJsonElement();
+ }
+
+ throw ThrowHelper.GetJsonElementWrongTypeException(JsonValueKind.Array, jsonNode.ValueKind);
}
}
@@ -74,7 +122,19 @@ public int GetArrayLength()
{
CheckValidInstance();
- return _parent.GetArrayLength(_idx);
+ if (_parent is JsonDocument document)
+ {
+ return document.GetArrayLength(_idx);
+ }
+
+ var jsonNode = (JsonNode)_parent;
+
+ if (jsonNode is JsonArray jsonArray)
+ {
+ return jsonArray.Count;
+ }
+
+ throw ThrowHelper.GetJsonElementWrongTypeException(JsonValueKind.Array, jsonNode.ValueKind);
}
///
@@ -264,7 +324,26 @@ public bool TryGetProperty(ReadOnlySpan propertyName, out JsonElement valu
{
CheckValidInstance();
- return _parent.TryGetNamedPropertyValue(_idx, propertyName, out value);
+ if (_parent is JsonDocument document)
+ {
+ return document.TryGetNamedPropertyValue(_idx, propertyName, out value);
+ }
+
+ var jsonNode = (JsonNode)_parent;
+
+ if (jsonNode is JsonObject jsonObject)
+ {
+ if (jsonObject.TryGetPropertyValue(propertyName.ToString(), out JsonNode nodeValue))
+ {
+ value = nodeValue.AsJsonElement();
+ return true;
+ }
+
+ value = default;
+ return false;
+ }
+
+ throw ThrowHelper.GetJsonElementWrongTypeException(JsonValueKind.Object, jsonNode.ValueKind);
}
///
@@ -300,7 +379,26 @@ public bool TryGetProperty(ReadOnlySpan utf8PropertyName, out JsonElement
{
CheckValidInstance();
- return _parent.TryGetNamedPropertyValue(_idx, utf8PropertyName, out value);
+ if (_parent is JsonDocument document)
+ {
+ return document.TryGetNamedPropertyValue(_idx, utf8PropertyName, out value);
+ }
+
+ var jsonNode = (JsonNode)_parent;
+
+ if (jsonNode is JsonObject jsonObject)
+ {
+ if (jsonObject.TryGetPropertyValue(JsonHelpers.Utf8GetString(utf8PropertyName), out JsonNode nodeValue))
+ {
+ value = nodeValue.AsJsonElement();
+ return true;
+ }
+
+ value = default;
+ return false;
+ }
+
+ throw ThrowHelper.GetJsonElementWrongTypeException(JsonValueKind.Object, jsonNode.ValueKind);
}
///
@@ -319,15 +417,26 @@ public bool TryGetProperty(ReadOnlySpan utf8PropertyName, out JsonElement
///
public bool GetBoolean()
{
- // CheckValidInstance is redundant. Asking for the type will
- // return None, which then throws the same exception in the return statement.
+ CheckValidInstance();
+
+ if (_parent is JsonDocument document)
+ {
+ JsonTokenType type = TokenType;
- JsonTokenType type = TokenType;
+ return
+ type == JsonTokenType.True ? true :
+ type == JsonTokenType.False ? false :
+ throw ThrowHelper.GetJsonElementWrongTypeException(nameof(Boolean), type);
+ }
+
+ var jsonNode = (JsonNode)_parent;
- return
- type == JsonTokenType.True ? true :
- type == JsonTokenType.False ? false :
- throw ThrowHelper.GetJsonElementWrongTypeException(nameof(Boolean), type);
+ if (_parent is JsonBoolean jsonBoolean)
+ {
+ return jsonBoolean.Value;
+ }
+
+ throw ThrowHelper.GetJsonElementWrongTypeException(nameof(Boolean), jsonNode.ValueKind);
}
///
@@ -348,7 +457,19 @@ public string GetString()
{
CheckValidInstance();
- return _parent.GetString(_idx, JsonTokenType.String);
+ if (_parent is JsonDocument document)
+ {
+ return document.GetString(_idx, JsonTokenType.String);
+ }
+
+ var jsonNode = (JsonNode)_parent;
+
+ if (jsonNode is JsonString jsonString)
+ {
+ return jsonString.Value;
+ }
+
+ throw ThrowHelper.GetJsonElementWrongTypeException(JsonValueKind.String, jsonNode.ValueKind);
}
///
@@ -356,7 +477,7 @@ public string GetString()
///
/// Receives the value.
///
- /// This method does not create a byte[] representation of values other than bsae 64 encoded JSON strings.
+ /// This method does not create a byte[] representation of values other than base 64 encoded JSON strings.
///
///
/// if the entire token value is encoded as valid Base64 text and can be successfully decoded to bytes.
@@ -372,7 +493,19 @@ public bool TryGetBytesFromBase64(out byte[] value)
{
CheckValidInstance();
- return _parent.TryGetValue(_idx, out value);
+ if (_parent is JsonDocument document)
+ {
+ return document.TryGetValue(_idx, out value);
+ }
+
+ var jsonNode = (JsonNode)_parent;
+
+ if (jsonNode is JsonString)
+ {
+ throw new NotSupportedException();
+ }
+
+ throw ThrowHelper.GetJsonElementWrongTypeException(JsonValueKind.String, jsonNode.ValueKind);
}
///
@@ -424,7 +557,19 @@ public bool TryGetSByte(out sbyte value)
{
CheckValidInstance();
- return _parent.TryGetValue(_idx, out value);
+ if (_parent is JsonDocument document)
+ {
+ return document.TryGetValue(_idx, out value);
+ }
+
+ var jsonNode = (JsonNode)_parent;
+
+ if (jsonNode is JsonNumber jsonNumber)
+ {
+ return jsonNumber.TryGetSByte(out value);
+ }
+
+ throw ThrowHelper.GetJsonElementWrongTypeException(JsonValueKind.Number, jsonNode.ValueKind);
}
///
@@ -472,7 +617,19 @@ public bool TryGetByte(out byte value)
{
CheckValidInstance();
- return _parent.TryGetValue(_idx, out value);
+ if (_parent is JsonDocument document)
+ {
+ return document.TryGetValue(_idx, out value);
+ }
+
+ var jsonNode = (JsonNode)_parent;
+
+ if (jsonNode is JsonNumber jsonNumber)
+ {
+ return jsonNumber.TryGetByte(out value);
+ }
+
+ throw ThrowHelper.GetJsonElementWrongTypeException(JsonValueKind.Number, jsonNode.ValueKind);
}
///
@@ -522,7 +679,19 @@ public bool TryGetInt16(out short value)
{
CheckValidInstance();
- return _parent.TryGetValue(_idx, out value);
+ if (_parent is JsonDocument document)
+ {
+ return document.TryGetValue(_idx, out value);
+ }
+
+ var jsonNode = (JsonNode)_parent;
+
+ if (_parent is JsonNumber jsonNumber)
+ {
+ return jsonNumber.TryGetInt16(out value);
+ }
+
+ throw ThrowHelper.GetJsonElementWrongTypeException(JsonValueKind.Number, jsonNode.ValueKind);
}
///
@@ -570,7 +739,19 @@ public bool TryGetUInt16(out ushort value)
{
CheckValidInstance();
- return _parent.TryGetValue(_idx, out value);
+ if (_parent is JsonDocument document)
+ {
+ return document.TryGetValue(_idx, out value);
+ }
+
+ var jsonNode = (JsonNode)_parent;
+
+ if (_parent is JsonNumber jsonNumber)
+ {
+ return jsonNumber.TryGetUInt16(out value);
+ }
+
+ throw ThrowHelper.GetJsonElementWrongTypeException(JsonValueKind.Number, jsonNode.ValueKind);
}
///
@@ -621,7 +802,19 @@ public bool TryGetInt32(out int value)
{
CheckValidInstance();
- return _parent.TryGetValue(_idx, out value);
+ if (_parent is JsonDocument document)
+ {
+ return document.TryGetValue(_idx, out value);
+ }
+
+ var jsonNode = (JsonNode)_parent;
+
+ if (jsonNode is JsonNumber jsonNumber)
+ {
+ return jsonNumber.TryGetInt32(out value);
+ }
+
+ throw ThrowHelper.GetJsonElementWrongTypeException(JsonValueKind.Number, jsonNode.ValueKind);
}
///
@@ -669,7 +862,19 @@ public bool TryGetUInt32(out uint value)
{
CheckValidInstance();
- return _parent.TryGetValue(_idx, out value);
+ if (_parent is JsonDocument document)
+ {
+ return document.TryGetValue(_idx, out value);
+ }
+
+ var jsonNode = (JsonNode)_parent;
+
+ if (jsonNode is JsonNumber jsonNumber)
+ {
+ return jsonNumber.TryGetUInt32(out value);
+ }
+
+ throw ThrowHelper.GetJsonElementWrongTypeException(JsonValueKind.Number, jsonNode.ValueKind);
}
///
@@ -720,7 +925,19 @@ public bool TryGetInt64(out long value)
{
CheckValidInstance();
- return _parent.TryGetValue(_idx, out value);
+ if (_parent is JsonDocument document)
+ {
+ return document.TryGetValue(_idx, out value);
+ }
+
+ var jsonNode = (JsonNode)_parent;
+
+ if (jsonNode is JsonNumber jsonNumber)
+ {
+ return jsonNumber.TryGetInt64(out value);
+ }
+
+ throw ThrowHelper.GetJsonElementWrongTypeException(JsonValueKind.Number, jsonNode.ValueKind);
}
///
@@ -771,7 +988,19 @@ public bool TryGetUInt64(out ulong value)
{
CheckValidInstance();
- return _parent.TryGetValue(_idx, out value);
+ if (_parent is JsonDocument document)
+ {
+ return document.TryGetValue(_idx, out value);
+ }
+
+ var jsonNode = (JsonNode)_parent;
+
+ if (jsonNode is JsonNumber jsonNumber)
+ {
+ return jsonNumber.TryGetUInt64(out value);
+ }
+
+ throw ThrowHelper.GetJsonElementWrongTypeException(JsonValueKind.Number, jsonNode.ValueKind);
}
///
@@ -831,7 +1060,19 @@ public bool TryGetDouble(out double value)
{
CheckValidInstance();
- return _parent.TryGetValue(_idx, out value);
+ if (_parent is JsonDocument document)
+ {
+ return document.TryGetValue(_idx, out value);
+ }
+
+ var jsonNode = (JsonNode)_parent;
+
+ if (_parent is JsonNumber jsonNumber)
+ {
+ return jsonNumber.TryGetDouble(out value);
+ }
+
+ throw ThrowHelper.GetJsonElementWrongTypeException(JsonValueKind.Number, jsonNode.ValueKind);
}
///
@@ -898,7 +1139,19 @@ public bool TryGetSingle(out float value)
{
CheckValidInstance();
- return _parent.TryGetValue(_idx, out value);
+ if (_parent is JsonDocument document)
+ {
+ return document.TryGetValue(_idx, out value);
+ }
+
+ var jsonNode = (JsonNode)_parent;
+
+ if (jsonNode is JsonNumber jsonNumber)
+ {
+ return jsonNumber.TryGetSingle(out value);
+ }
+
+ throw ThrowHelper.GetJsonElementWrongTypeException(JsonValueKind.Number, jsonNode.ValueKind);
}
///
@@ -957,7 +1210,19 @@ public bool TryGetDecimal(out decimal value)
{
CheckValidInstance();
- return _parent.TryGetValue(_idx, out value);
+ if (_parent is JsonDocument document)
+ {
+ return document.TryGetValue(_idx, out value);
+ }
+
+ var jsonNode = (JsonNode)_parent;
+
+ if (jsonNode is JsonNumber jsonNumber)
+ {
+ return jsonNumber.TryGetDecimal(out value);
+ }
+
+ throw ThrowHelper.GetJsonElementWrongTypeException(JsonValueKind.Number, jsonNode.ValueKind);
}
///
@@ -1008,7 +1273,19 @@ public bool TryGetDateTime(out DateTime value)
{
CheckValidInstance();
- return _parent.TryGetValue(_idx, out value);
+ if (_parent is JsonDocument document)
+ {
+ return document.TryGetValue(_idx, out value);
+ }
+
+ var jsonNode = (JsonNode)_parent;
+
+ if (jsonNode is JsonString jsonString)
+ {
+ return jsonString.TryGetDateTime(out value);
+ }
+
+ throw ThrowHelper.GetJsonElementWrongTypeException(JsonValueKind.String, jsonNode.ValueKind);
}
///
@@ -1059,7 +1336,19 @@ public bool TryGetDateTimeOffset(out DateTimeOffset value)
{
CheckValidInstance();
- return _parent.TryGetValue(_idx, out value);
+ if (_parent is JsonDocument document)
+ {
+ return document.TryGetValue(_idx, out value);
+ }
+
+ var jsonNode = (JsonNode)_parent;
+
+ if (jsonNode is JsonString jsonString)
+ {
+ return jsonString.TryGetDateTimeOffset(out value);
+ }
+
+ throw ThrowHelper.GetJsonElementWrongTypeException(JsonValueKind.String, jsonNode.ValueKind);
}
///
@@ -1110,7 +1399,19 @@ public bool TryGetGuid(out Guid value)
{
CheckValidInstance();
- return _parent.TryGetValue(_idx, out value);
+ if (_parent is JsonDocument document)
+ {
+ return document.TryGetValue(_idx, out value);
+ }
+
+ var jsonNode = (JsonNode)_parent;
+
+ if (jsonNode is JsonString jsonString)
+ {
+ return jsonString.TryGetGuid(out value);
+ }
+
+ throw ThrowHelper.GetJsonElementWrongTypeException(JsonValueKind.String, jsonNode.ValueKind);
}
///
@@ -1144,7 +1445,8 @@ internal string GetPropertyName()
{
CheckValidInstance();
- return _parent.GetNameOfPropertyValue(_idx);
+ var document = (JsonDocument)_parent;
+ return document.GetNameOfPropertyValue(_idx);
}
///
@@ -1160,14 +1462,21 @@ public string GetRawText()
{
CheckValidInstance();
- return _parent.GetRawValueAsString(_idx);
+ if (_parent is JsonDocument document)
+ {
+ return document.GetRawValueAsString(_idx);
+ }
+
+ var jsonNode = (JsonNode)_parent;
+ return jsonNode.ToString();
}
internal string GetPropertyRawText()
{
CheckValidInstance();
- return _parent.GetPropertyRawValueAsString(_idx);
+ var document = (JsonDocument)_parent;
+ return document.GetPropertyRawValueAsString(_idx);
}
///
@@ -1258,14 +1567,16 @@ internal bool TextEqualsHelper(ReadOnlySpan utf8Text, bool isPropertyName)
{
CheckValidInstance();
- return _parent.TextEquals(_idx, utf8Text, isPropertyName);
+ var document = (JsonDocument)_parent;
+ return document.TextEquals(_idx, utf8Text, isPropertyName);
}
internal bool TextEqualsHelper(ReadOnlySpan text, bool isPropertyName)
{
CheckValidInstance();
- return _parent.TextEquals(_idx, text, isPropertyName);
+ var document = (JsonDocument)_parent;
+ return document.TextEquals(_idx, text, isPropertyName);
}
///
@@ -1290,7 +1601,8 @@ public void WriteTo(Utf8JsonWriter writer)
CheckValidInstance();
- _parent.WriteElementTo(_idx, writer);
+ var document = (JsonDocument)_parent;
+ document.WriteElementTo(_idx, writer);
}
///
@@ -1309,11 +1621,21 @@ public ArrayEnumerator EnumerateArray()
{
CheckValidInstance();
- JsonTokenType tokenType = TokenType;
+ if (_parent is JsonDocument)
+ {
+ JsonTokenType tokenType = TokenType;
- if (tokenType != JsonTokenType.StartArray)
+ if (tokenType != JsonTokenType.StartArray)
+ {
+ throw ThrowHelper.GetJsonElementWrongTypeException(JsonTokenType.StartArray, tokenType);
+ }
+ }
+ else if (_parent is JsonNode node)
{
- throw ThrowHelper.GetJsonElementWrongTypeException(JsonTokenType.StartArray, tokenType);
+ if (node.ValueKind != JsonValueKind.Array)
+ {
+ throw new InvalidOperationException();
+ }
}
return new ArrayEnumerator(this);
@@ -1335,11 +1657,21 @@ public ObjectEnumerator EnumerateObject()
{
CheckValidInstance();
- JsonTokenType tokenType = TokenType;
+ if (_parent is JsonDocument)
+ {
+ JsonTokenType tokenType = TokenType;
- if (tokenType != JsonTokenType.StartObject)
+ if (tokenType != JsonTokenType.StartObject)
+ {
+ throw ThrowHelper.GetJsonElementWrongTypeException(JsonTokenType.StartObject, tokenType);
+ }
+ }
+ else if (_parent is JsonNode node)
{
- throw ThrowHelper.GetJsonElementWrongTypeException(JsonTokenType.StartObject, tokenType);
+ if (node.ValueKind != JsonValueKind.Object)
+ {
+ throw new InvalidOperationException();
+ }
}
return new ObjectEnumerator(this);
@@ -1392,7 +1724,13 @@ public override string ToString()
{
// null parent should have hit the None case
Debug.Assert(_parent != null);
- return _parent.GetRawValueAsString(_idx);
+ if (_parent is JsonDocument document)
+ {
+ return document.GetRawValueAsString(_idx);
+ }
+
+ var jsonNode = (JsonNode)_parent;
+ return jsonNode.ToString();
}
case JsonTokenType.String:
return GetString();
@@ -1422,12 +1760,18 @@ public JsonElement Clone()
{
CheckValidInstance();
- if (!_parent.IsDisposable)
+ if (_parent is JsonDocument document)
{
- return this;
+ if (!document.IsDisposable)
+ {
+ return this;
+ }
+
+ return document.CloneElement(_idx);
}
- return _parent.CloneElement(_idx);
+ var jsonNode = (JsonNode)_parent;
+ return jsonNode.Clone().AsJsonElement();
}
private void CheckValidInstance()
@@ -1436,6 +1780,8 @@ private void CheckValidInstance()
{
throw new InvalidOperationException();
}
+
+ Debug.Assert(_parent is JsonDocument || _parent is JsonNode);
}
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
diff --git a/src/System.Text.Json/src/System/Text/Json/Document/JsonProperty.cs b/src/System.Text.Json/src/System/Text/Json/Document/JsonProperty.cs
index 79d8fd810809..ac6265df3444 100644
--- a/src/System.Text.Json/src/System/Text/Json/Document/JsonProperty.cs
+++ b/src/System.Text.Json/src/System/Text/Json/Document/JsonProperty.cs
@@ -17,16 +17,18 @@ public readonly struct JsonProperty
/// The value of this property.
///
public JsonElement Value { get; }
+ private string _name { get; }
- internal JsonProperty(JsonElement value)
+ internal JsonProperty(JsonElement value, string name = null)
{
Value = value;
+ _name = name;
}
///
/// The name of this property.
///
- public string Name => Value.GetPropertyName();
+ public string Name => _name ?? Value.GetPropertyName();
///
/// Compares to the name of this property.
diff --git a/src/System.Text.Json/src/System/Text/Json/Node/JsonArray.cs b/src/System.Text.Json/src/System/Text/Json/Node/JsonArray.cs
new file mode 100644
index 000000000000..13b7b7a6a01e
--- /dev/null
+++ b/src/System.Text.Json/src/System/Text/Json/Node/JsonArray.cs
@@ -0,0 +1,583 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Collections;
+using System.Collections.Generic;
+
+namespace System.Text.Json
+{
+ ///
+ /// Represents a JSON array.
+ ///
+ public sealed class JsonArray : JsonNode, IList, IReadOnlyList
+ {
+ internal readonly List _list;
+ internal int _version;
+
+ ///
+ /// Initializes a new instance of the class representing the empty array.
+ ///
+ public JsonArray()
+ {
+ _list = new List();
+ _version = 0;
+ }
+
+ ///
+ /// Initializes a new instance of the class representing the specified collection.
+ ///
+ /// Collection to represent.
+ public JsonArray(IEnumerable values)
+ {
+ _list = new List(values);
+ _version = 0;
+ }
+
+ ///
+ /// Initializes a new instance of the class representing the specified collection of s.
+ ///
+ /// Collection to represent.
+ ///
+ /// Some of provided values are null.
+ ///
+ public JsonArray(IEnumerable values) : this()
+ {
+ foreach (string value in values)
+ {
+ if (value == null)
+ {
+ _list.Add(null);
+ }
+
+ _list.Add(new JsonString(value));
+ }
+ }
+
+ ///
+ /// Initializes a new instance of the class representing the specified collection of s.
+ ///
+ /// Collection to represent.
+ public JsonArray(IEnumerable values) : this()
+ {
+ foreach (bool value in values)
+ {
+ _list.Add(new JsonBoolean(value));
+ }
+ }
+
+ ///
+ /// Initializes a new instance of the class representing the specified collection of s.
+ ///
+ /// Collection to represent.
+ public JsonArray(IEnumerable values) : this()
+ {
+ foreach (byte value in values)
+ {
+ _list.Add(new JsonNumber(value));
+ }
+ }
+
+ ///
+ /// Initializes a new instance of the class representing the specified collection of s.
+ ///
+ /// Collection to represent.
+ public JsonArray(IEnumerable values) : this()
+ {
+ foreach (short value in values)
+ {
+ _list.Add(new JsonNumber(value));
+ }
+ }
+
+ ///
+ /// Initializes a new instance of the class representing the specified collection of s.
+ ///
+ /// Collection to represent.
+ public JsonArray(IEnumerable values) : this()
+ {
+ foreach (int value in values)
+ {
+ _list.Add(new JsonNumber(value));
+ }
+ }
+
+ ///
+ /// Initializes a new instance of the class representing the specified collection of s.
+ ///
+ /// Collection to represent.
+ public JsonArray(IEnumerable values) : this()
+ {
+ foreach (long value in values)
+ {
+ _list.Add(new JsonNumber(value));
+ }
+ }
+
+ ///
+ /// Initializes a new instance of the class representing the specified collection of s.
+ ///
+ /// Collection to represent.
+ ///
+ /// Some of provided values are not in a legal JSON number format.
+ ///
+ public JsonArray(IEnumerable values) : this()
+ {
+ foreach (float value in values)
+ {
+ _list.Add(new JsonNumber(value));
+ }
+ }
+
+ ///
+ /// Initializes a new instance of the class representing the specified collection of s.
+ ///
+ /// Collection to represent.
+ ///
+ /// Some of provided values are not in a legal JSON number format.
+ ///
+ public JsonArray(IEnumerable values) : this()
+ {
+ foreach (double value in values)
+ {
+ _list.Add(new JsonNumber(value));
+ }
+ }
+
+ ///
+ /// Initializes a new instance of the class representing the specified collection of s.
+ ///
+ /// Collection to represent.
+ [CLSCompliant(false)]
+ public JsonArray(IEnumerable values) : this()
+ {
+ foreach (sbyte value in values)
+ {
+ _list.Add(new JsonNumber(value));
+ }
+ }
+
+ ///
+ /// Initializes a new instance of the class representing the specified collection of s.
+ ///
+ /// Collection to represent.
+ [CLSCompliant(false)]
+ public JsonArray(IEnumerable values) : this()
+ {
+ foreach (ushort value in values)
+ {
+ _list.Add(new JsonNumber(value));
+ }
+ }
+
+ ///
+ /// Initializes a new instance of the class representing the specified collection of s.
+ ///
+ /// Collection to represent.
+ [CLSCompliant(false)]
+ public JsonArray(IEnumerable values) : this()
+ {
+ foreach (uint value in values)
+ {
+ _list.Add(new JsonNumber(value));
+ }
+ }
+
+ ///
+ /// Initializes a new instance of the class representing the specified collection of s.
+ ///
+ /// Collection to represent.
+ [CLSCompliant(false)]
+ public JsonArray(IEnumerable values) : this()
+ {
+ foreach (ulong value in values)
+ {
+ _list.Add(new JsonNumber(value));
+ }
+ }
+
+ ///
+ /// Initializes a new instance of the class representing the specified collection of s.
+ ///
+ /// Collection to represent.
+ public JsonArray(IEnumerable values) : this()
+ {
+ foreach (decimal value in values)
+ {
+ _list.Add(new JsonNumber(value));
+ }
+ }
+
+ ///
+ /// Gets or sets the element at the specified index.
+ ///
+ /// The zero-based index of the element to get or set.
+ ///
+ /// Index is less than 0.
+ ///
+ public JsonNode this[int idx]
+ {
+ get => _list[idx];
+ set
+ {
+ _list[idx] = value;
+ _version++;
+ }
+ }
+
+ ///
+ /// Adds the specified value as the last item in this collection.
+ ///
+ /// The value to add.
+ /// Null value is allowed and represents the JSON null value.
+ public void Add(JsonNode value)
+ {
+ _list.Add(value);
+ _version++;
+ }
+
+ ///
+ /// Adds the specified value as a as the last item in this collection.
+ ///
+ /// The value to add.
+ /// Null value is allowed and represents the JSON null value.
+ public void Add(string value)
+ {
+ if (value == null)
+ {
+ Add((JsonNode)null);
+ }
+ else
+ {
+ Add(new JsonString(value));
+ }
+ }
+
+ ///
+ /// Adds the specified value as a as the last item in this collection.
+ ///
+ /// The value to add.
+ public void Add(bool value) => Add(new JsonBoolean(value));
+
+ ///
+ /// Adds the specified value as a as the last item in this collection.
+ ///
+ /// The value to add.
+ public void Add(byte value) => Add(new JsonNumber(value));
+
+ ///
+ /// Adds the specified value as a as the last item in this collection.
+ ///
+ /// The value to add.
+ public void Add(short value) => Add(new JsonNumber(value));
+
+ ///
+ /// Adds the specified value as a as the last item in this collection.
+ ///
+ /// The value to add.
+ public void Add(int value) => Add(new JsonNumber(value));
+
+ ///
+ /// Adds the specified value as a as the last item in this collection.
+ ///
+ /// The value to add.
+ public void Add(long value) => Add(new JsonNumber(value));
+
+ ///
+ /// Adds the specified value as a as the last item in this collection.
+ ///
+ /// The value to add.
+ ///
+ /// Provided value is not in a legal JSON number format.
+ ///
+ public void Add(float value) => Add(new JsonNumber(value));
+
+ ///
+ /// Adds the specified value as a as the last item in this collection.
+ ///
+ /// The value to add.
+ ///
+ /// Provided value is not in a legal JSON number format.
+ ///
+ public void Add(double value) => Add(new JsonNumber(value));
+
+ ///
+ /// Adds the specified value as a as the last item in this collection.
+ ///
+ /// The value to add.
+ [CLSCompliant(false)]
+ public void Add(sbyte value) => Add(new JsonNumber(value));
+
+ ///
+ /// Adds the specified value as a as the last item in this collection.
+ ///
+ /// The value to add.
+ [CLSCompliant(false)]
+ public void Add(ushort value) => Add(new JsonNumber(value));
+
+ ///
+ /// Adds the specified value as a as the last item in this collection.
+ ///
+ /// The value to add.
+ [CLSCompliant(false)]
+ public void Add(uint value) => Add(new JsonNumber(value));
+
+ ///
+ /// Adds the specified value as a as the last item in this collection.
+ ///
+ /// The value to add.
+ [CLSCompliant(false)]
+ public void Add(ulong value) => Add(new JsonNumber(value));
+
+ ///
+ /// Adds the specified value as a as the last item in this collection.
+ ///
+ /// The value to add.
+ public void Add(decimal value) => Add(new JsonNumber(value));
+
+ ///
+ /// Inserts the specified item at the specified index of the JSON array.
+ ///
+ /// The zero-based index at which should be inserted.
+ /// The item to add.
+ /// The parameter may be , which represents the JSON null value.
+ public void Insert(int index, JsonNode item)
+ {
+ _list.Insert(index, item);
+ _version++;
+ }
+
+ ///
+ /// Inserts the specified item as a at the specified index of the collection.
+ ///
+ /// The zero-based index at which should be inserted.
+ /// The item to add.
+ public void Insert(int index, string item) => Insert(index, new JsonString(item));
+
+ ///
+ /// Inserts the specified item as a at the specified index of the collection.
+ ///
+ /// The zero-based index at which should be inserted.
+ /// The item to add.
+ public void Insert(int index, bool item) => Insert(index, new JsonBoolean(item));
+
+ ///
+ /// Inserts the specified item as a at the specified index of the collection.
+ ///
+ /// The zero-based index at which should be inserted.
+ /// The item to add.
+ public void Insert(int index, byte item) => Insert(index, new JsonNumber(item));
+
+ ///
+ /// Inserts the specified item as a at the specified index of the collection.
+ ///
+ /// The zero-based index at which should be inserted.
+ /// The item to add.
+ public void Insert(int index, short item) => Insert(index, new JsonNumber(item));
+
+ ///
+ /// Inserts the specified item as a at the specified index of the collection.
+ ///
+ /// The zero-based index at which should be inserted.
+ /// The item to add.
+ public void Insert(int index, int item) => Insert(index, new JsonNumber(item));
+
+ ///
+ /// Inserts the specified item as a at the specified index of the collection.
+ ///
+ /// The zero-based index at which should be inserted.
+ /// The item to add.
+ public void Insert(int index, long item) => Insert(index, new JsonNumber(item));
+
+ ///
+ /// Inserts the specified item as a at the specified index of the collection.
+ ///
+ /// The zero-based index at which should be inserted.
+ /// The item to add.
+ ///
+ /// Provided value is not in a legal JSON number format.
+ ///
+ public void Insert(int index, float item) => Insert(index, new JsonNumber(item));
+
+ ///
+ /// Inserts the specified item as a at the specified index of the collection.
+ ///
+ /// The zero-based index at which should be inserted.
+ /// The item to add.
+ ///
+ /// Provided value is not in a legal JSON number format.
+ ///
+ public void Insert(int index, double item) => Insert(index, new JsonNumber(item));
+
+ ///
+ /// Inserts the specified item as a at the specified index of the collection.
+ ///
+ /// The zero-based index at which should be inserted.
+ /// The item to add.
+ [CLSCompliant(false)]
+ public void Insert(int index, sbyte item) => Insert(index, new JsonNumber(item));
+
+ ///
+ /// Inserts the specified item as a at the specified index of the collection.
+ ///
+ /// The zero-based index at which should be inserted.
+ /// The item to add.
+ [CLSCompliant(false)]
+ public void Insert(int index, ushort item) => Insert(index, new JsonNumber(item));
+
+ ///
+ /// Inserts the specified item as a at the specified index of the collection.
+ ///
+ /// The zero-based index at which should be inserted.
+ /// The item to add.
+ [CLSCompliant(false)]
+ public void Insert(int index, uint item) => Insert(index, new JsonNumber(item));
+
+ ///
+ /// Inserts the specified item as a at the specified index of the collection.
+ ///
+ /// The zero-based index at which should be inserted.
+ /// The item to add.
+ [CLSCompliant(false)]
+ public void Insert(int index, ulong item) => Insert(index, new JsonNumber(item));
+
+ ///
+ /// Inserts the specified item as a at the specified index of the collection.
+ ///
+ /// The zero-based index at which should be inserted.
+ /// The item to add.
+ public void Insert(int index, decimal item) => Insert(index, new JsonNumber(item));
+
+ ///
+ /// Determines whether a specified element is in a collection.
+ ///
+ /// Value to check.
+ ///
+ /// if the value is successfully found in a collection,
+ /// otherwise.
+ ///
+ public bool Contains(JsonNode value) => _list.Contains(value);
+
+ ///
+ /// Gets the number of elements contained in the collection.
+ ///
+ public int Count => _list.Count;
+
+ ///
+ /// Gets a value indicating whether the collection is read-only.
+ ///
+ public bool IsReadOnly => false;
+
+ ///
+ /// Returns the zero-based index of the first occurrence of a specified item in the collection.
+ ///
+ /// Item to find.
+ /// The zero-based starting index of the search. 0 (zero) is valid in an empty collection.
+ public int IndexOf(JsonNode item) => _list.IndexOf(item);
+
+ ///
+ /// Returns the zero-based index of the last occurrence of a specified item in the collection.
+ ///
+ /// Item to find.
+ /// The zero-based starting index of the search. 0 (zero) is valid in an empty collection.
+ public int LastIndexOf(JsonNode item) => _list.LastIndexOf(item);
+
+ ///
+ /// Removes all elements from the JSON array.
+ ///
+ public void Clear()
+ {
+ _list.Clear();
+ _version++;
+ }
+
+ ///
+ /// Removes the first occurrence of a specific object from the collection.
+ ///
+ ///
+ /// The object to remove from the collection. The value can be null and it represents null collection.
+ ///
+ ///
+ /// if the item is successfully found in a collection and removed,
+ /// otherwise.
+ ///
+ public bool Remove(JsonNode item)
+ {
+ _version++;
+ return _list.Remove(item);
+ }
+
+ ///
+ /// Removes all the elements that match the conditions defined by the specified predicate.
+ ///
+ ///
+ /// Thepredicate delegate that defines the conditions of the elements to remove.
+ ///
+ /// The number of elements removed from the collection.
+ public int RemoveAll(Predicate match)
+ {
+ _version++;
+ return _list.RemoveAll(match);
+ }
+ ///
+ /// Removes the item at the specified index of the collection.
+ ///
+ ///
+ /// The zero-based index of the element to remove.
+ ///
+ public void RemoveAt(int index)
+ {
+ _list.RemoveAt(index);
+ _version++;
+ }
+
+ ///
+ /// Copies the collection or a portion of it to an array.
+ ///
+ ///
+ /// The one-dimensional array that is the destination of the elements copied from collection.
+ /// The array must have zero-based indexing.
+ ///
+ /// The zero-based index in array at which copying begins.
+ void ICollection.CopyTo(JsonNode[] array, int arrayIndex) => _list.CopyTo(array, arrayIndex);
+
+ ///
+ /// Returns an enumerator that iterates through the collection values.
+ ///
+ /// An enumerator structure for the .
+ IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
+
+ ///
+ /// Returns an enumerator that iterates through the collection values.
+ ///
+ /// An enumerator structure for the .
+ IEnumerator IEnumerable.GetEnumerator() => new JsonArrayEnumerator(this);
+
+ ///
+ /// Returns an enumerator that iterates through the collection values.
+ ///
+ /// An enumerator structure for the .
+ public JsonArrayEnumerator GetEnumerator() => new JsonArrayEnumerator(this);
+
+ ///
+ /// Creates a new collection that is a copy of the current instance.
+ ///
+ /// A new collection that is a copy of this instance.
+ public override JsonNode Clone()
+ {
+ var jsonArray = new JsonArray();
+
+ foreach (JsonNode jsonNode in _list)
+ {
+ jsonArray.Add(jsonNode.Clone());
+ }
+
+ return jsonArray;
+ }
+
+ ///
+ /// Returns
+ ///
+ public override JsonValueKind ValueKind { get => JsonValueKind.Array;}
+ }
+}
diff --git a/src/System.Text.Json/src/System/Text/Json/Node/JsonArrayEnumerator.cs b/src/System.Text.Json/src/System/Text/Json/Node/JsonArrayEnumerator.cs
new file mode 100644
index 000000000000..1dc16a232173
--- /dev/null
+++ b/src/System.Text.Json/src/System/Text/Json/Node/JsonArrayEnumerator.cs
@@ -0,0 +1,45 @@
+using System.Collections;
+using System.Collections.Generic;
+
+namespace System.Text.Json
+{
+ ///
+ /// Supports an iteration over a JSON array.
+ ///
+ public struct JsonArrayEnumerator : IEnumerator
+ {
+ private List.Enumerator _enumerator;
+
+ ///
+ /// Initializes a new instance of the class supporting an interation over provided JSON array.
+ ///
+ /// JSON array to iterate over.
+ public JsonArrayEnumerator(JsonArray jsonArray) => _enumerator = jsonArray._list.GetEnumerator();
+
+ ///
+ /// Gets the property in the JSON array at the current position of the enumerator.
+ ///
+ public JsonNode Current => _enumerator.Current;
+
+ ///
+ /// Gets the property in the JSON array at the current position of the enumerator.
+ ///
+ object IEnumerator.Current => _enumerator.Current;
+
+ ///
+ /// Releases all resources used by the .
+ ///
+ public void Dispose() => _enumerator.Dispose();
+
+ ///
+ /// Advances the enumerator to the next property of the JSON array.
+ ///
+ ///
+ public bool MoveNext() => _enumerator.MoveNext();
+
+ ///
+ /// Sets the enumerator to its initial position, which is before the first element in the JSON array.
+ ///
+ void IEnumerator.Reset() => ((IEnumerator)_enumerator).Reset();
+ }
+}
diff --git a/src/System.Text.Json/src/System/Text/Json/Node/JsonBoolean.cs b/src/System.Text.Json/src/System/Text/Json/Node/JsonBoolean.cs
index 985ed4843def..7a358dd34c9b 100644
--- a/src/System.Text.Json/src/System/Text/Json/Node/JsonBoolean.cs
+++ b/src/System.Text.Json/src/System/Text/Json/Node/JsonBoolean.cs
@@ -94,5 +94,16 @@ public sealed class JsonBoolean : JsonNode, IEquatable
/// otherwise.
///
public static bool operator !=(JsonBoolean left, JsonBoolean right) => !(left == right);
+
+ ///
+ /// Creates a new JSON boolean that is a copy of the current instance.
+ ///
+ /// A new JSON boolean that is a copy of this instance.
+ public override JsonNode Clone() => new JsonBoolean(Value);
+
+ ///
+ /// Returns or , accordingly to the represented value.
+ ///
+ public override JsonValueKind ValueKind { get => Value ? JsonValueKind.True : JsonValueKind.False; }
}
}
diff --git a/src/System.Text.Json/src/System/Text/Json/Node/JsonNode.cs b/src/System.Text.Json/src/System/Text/Json/Node/JsonNode.cs
index ec16a6642c76..c07584082e88 100644
--- a/src/System.Text.Json/src/System/Text/Json/Node/JsonNode.cs
+++ b/src/System.Text.Json/src/System/Text/Json/Node/JsonNode.cs
@@ -2,6 +2,8 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Diagnostics;
+
namespace System.Text.Json
{
///
@@ -10,5 +12,112 @@ namespace System.Text.Json
public abstract class JsonNode
{
private protected JsonNode() { }
+
+ ///
+ /// Transforms this instance into representation.
+ /// Operations performed on this instance will modify the returned .
+ ///
+ /// Mutable with underneath.
+ public JsonElement AsJsonElement() => new JsonElement(this);
+
+ ///
+ /// The that the node is.
+ ///
+ public abstract JsonValueKind ValueKind { get; }
+
+ ///
+ /// Gets the represented by .
+ /// Operations performed on the returned will modify the .
+ ///
+ /// to get the from.
+ /// represented by .
+ public static JsonNode GetNode(JsonElement jsonElement) => (JsonNode)jsonElement._parent;
+
+ ///
+ /// Gets the represented by the .
+ /// Operations performed on the returned will modify the .
+ /// A return value indicates whether the operation succeeded.
+ ///
+ /// to get the from.
+ /// represented by .
+ ///
+ /// if the operation succeded;
+ /// otherwise,
+ ///
+ public static bool TryGetNode(JsonElement jsonElement, out JsonNode jsonNode)
+ {
+ if (!jsonElement.IsImmutable)
+ {
+ jsonNode = (JsonNode)jsonElement._parent;
+ return true;
+ }
+
+ jsonNode = null;
+ return false;
+ }
+
+ ///
+ /// Parses a string representiong JSON document into .
+ ///
+ /// JSON to parse.
+ /// representation of .
+ public static JsonNode Parse(string json)
+ {
+ using (JsonDocument document = JsonDocument.Parse(json))
+ {
+ return DeepCopy(document.RootElement);
+ }
+ }
+
+ ///
+ /// Performs a deep copy operation on this instance.
+ ///
+ /// which is a clone of this instance.
+ public abstract JsonNode Clone();
+
+ ///
+ /// Performs a deep copy operation on returning corresponding modifiable tree structure of JSON nodes.
+ /// Operations performed on returned does not modify .
+ ///
+ /// to copy.
+ /// representing .
+ public static JsonNode DeepCopy(JsonElement jsonElement)
+ {
+ if (!jsonElement.IsImmutable)
+ {
+ return GetNode(jsonElement).Clone();
+ }
+
+ switch (jsonElement.ValueKind)
+ {
+ case JsonValueKind.Object:
+ JsonObject jsonObject = new JsonObject();
+ foreach (JsonProperty property in jsonElement.EnumerateObject())
+ {
+ jsonObject.Add(property.Name, DeepCopy(property.Value));
+ }
+ return jsonObject;
+ case JsonValueKind.Array:
+ JsonArray jsonArray = new JsonArray();
+ foreach (JsonElement element in jsonElement.EnumerateArray())
+ {
+ jsonArray.Add(DeepCopy(element));
+ }
+ return jsonArray;
+ case JsonValueKind.Number:
+ return new JsonNumber(jsonElement.GetRawText());
+ case JsonValueKind.String:
+ return new JsonString(jsonElement.GetString());
+ case JsonValueKind.True:
+ return new JsonBoolean(true);
+ case JsonValueKind.False:
+ return new JsonBoolean(false);
+ case JsonValueKind.Null:
+ return null;
+ default:
+ Debug.Assert(jsonElement.ValueKind == JsonValueKind.Undefined, "No handler for JsonValueKind.{jsonElement.ValueKind}");
+ throw ThrowHelper.GetJsonElementWrongTypeException(JsonValueKind.Undefined, jsonElement.ValueKind);
+ }
+ }
}
}
diff --git a/src/System.Text.Json/src/System/Text/Json/Node/JsonNumber.cs b/src/System.Text.Json/src/System/Text/Json/Node/JsonNumber.cs
index a4c639d6da35..041131cccb2b 100644
--- a/src/System.Text.Json/src/System/Text/Json/Node/JsonNumber.cs
+++ b/src/System.Text.Json/src/System/Text/Json/Node/JsonNumber.cs
@@ -684,5 +684,16 @@ public void SetDouble(double value)
/// otherwise.
///
public static bool operator !=(JsonNumber left, JsonNumber right) => !(left == right);
+
+ ///
+ /// Creates a new JSON number that is a copy of the current instance.
+ ///
+ /// A new JSON number that is a copy of this instance.
+ public override JsonNode Clone() => new JsonNumber(_value);
+
+ ///
+ /// Returns
+ ///
+ public override JsonValueKind ValueKind { get => JsonValueKind.Number; }
}
}
diff --git a/src/System.Text.Json/src/System/Text/Json/Node/JsonObject.cs b/src/System.Text.Json/src/System/Text/Json/Node/JsonObject.cs
index 19a35a163fc1..90e456b7d3ad 100644
--- a/src/System.Text.Json/src/System/Text/Json/Node/JsonObject.cs
+++ b/src/System.Text.Json/src/System/Text/Json/Node/JsonObject.cs
@@ -67,15 +67,6 @@ public JsonNode this[string propertyName]
}
}
- ///
- /// Returns an enumerator that iterates through the JSON object properties.
- ///
- /// An enumerator structure for the JSON object.
- ///
- /// Property name to set already exists if handling duplicates is set to .
- ///
- public IEnumerator> GetEnumerator() => new JsonObjectEnumerator(this);
-
///
/// Adds the specified property to the JSON object.
///
@@ -139,7 +130,7 @@ public void Add(string propertyName, JsonNode propertyValue)
/// Adds the specified property as a to the JSON object.
///
/// Name of the property to add.
- /// value of the property to add.
+ /// value of the property to add.
///
/// Property name to set already exists if handling duplicates is set to .
///
@@ -371,6 +362,27 @@ public void AddRange(IEnumerable> jsonProperties)
}
}
+ ///
+ /// Adds the property values from the specified collection as a property to the JSON object.
+ ///
+ /// Name of the property to add.
+ /// Properties to add.
+ ///
+ /// Provided collection contains duplicates if handling duplicates is set to .
+ ///
+ ///
+ /// Some of property names are null.
+ ///
+ public void Add(string propertyName, IEnumerable propertyValues)
+ {
+ var jsonArray = new JsonArray();
+ foreach (JsonNode value in propertyValues)
+ {
+ jsonArray.Add(value);
+ }
+ Add(propertyName, (JsonNode)jsonArray);
+ }
+
///
/// Removes the property with the specified name.
///
@@ -438,7 +450,7 @@ public JsonNode GetPropertyValue(string propertyName)
///
/// Property with specified name is not found in JSON object.
///
- ///
+ ///
/// Property with specified name is not a JSON object.
///
public JsonObject GetJsonObjectPropertyValue(string propertyName)
@@ -448,7 +460,7 @@ public JsonObject GetJsonObjectPropertyValue(string propertyName)
return jsonObject;
}
- throw new InvalidCastException(SR.Format(SR.PropertyTypeMismatch, propertyName));
+ throw new ArgumentException(SR.Format(SR.PropertyTypeMismatch, propertyName));
}
///
@@ -464,17 +476,56 @@ public bool TryGetJsonObjectPropertyValue(string propertyName, out JsonObject js
{
if (TryGetPropertyValue(propertyName, out JsonNode jsonNode))
{
- if (jsonNode is JsonObject jsonNodeCasted)
- {
- jsonObject = jsonNodeCasted;
- return true;
- }
+ jsonObject = jsonNode as JsonObject;
+ return jsonObject != null;
}
jsonObject = null;
return false;
}
+ ///
+ /// Returns the JSON array value of a property with the specified name.
+ ///
+ /// Name of the property to return.
+ /// JSON objectvalue of a property with the specified name.
+ ///
+ /// Property with specified name is not found in JSON array.
+ ///
+ ///
+ /// Property with specified name is not a JSON array.
+ ///
+ public JsonArray GetJsonArrayPropertyValue(string propertyName)
+ {
+ if (GetPropertyValue(propertyName) is JsonArray jsonArray)
+ {
+ return jsonArray;
+ }
+
+ throw new ArgumentException(SR.Format(SR.PropertyTypeMismatch, propertyName));
+ }
+
+ ///
+ /// Returns the JSON array value of a property with the specified name.
+ ///
+ /// Name of the property to return.
+ /// JSON array value of the property with specified name.
+ ///
+ /// if JSON array property with specified name was found;
+ /// otherwise,
+ ///
+ public bool TryGetJsonArrayPropertyValue(string propertyName, out JsonArray jsonArray)
+ {
+ if (TryGetPropertyValue(propertyName, out JsonNode jsonNode))
+ {
+ jsonArray = jsonNode as JsonArray;
+ return jsonArray != null;
+ }
+
+ jsonArray = null;
+ return false;
+ }
+
///
/// A collection containing the property names of JSON object.
///
@@ -489,6 +540,48 @@ public bool TryGetJsonObjectPropertyValue(string propertyName, out JsonObject js
/// Returns an enumerator that iterates through the JSON object properties.
///
/// An enumerator structure for the .
- IEnumerator IEnumerable.GetEnumerator() => new JsonObjectEnumerator(this);
+ ///
+ /// Property name to set already exists if handling duplicates is set to .
+ ///
+ IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
+
+ ///
+ /// Returns an enumerator that iterates through the JSON object properties.
+ ///
+ /// An enumerator structure for the JSON object.
+ ///
+ /// Property name to set already exists if handling duplicates is set to .
+ ///
+ IEnumerator> IEnumerable>.GetEnumerator() => new JsonObjectEnumerator(this);
+
+ ///
+ /// Returns an enumerator that iterates through the JSON object properties.
+ ///
+ /// An enumerator structure for the JSON object.
+ ///
+ /// Property name to set already exists if handling duplicates is set to .
+ ///
+ public JsonObjectEnumerator GetEnumerator() => new JsonObjectEnumerator(this);
+
+ ///
+ /// Creates a new JSON object that is a copy of the current instance.
+ ///
+ /// A new JSON object that is a copy of this instance.
+ public override JsonNode Clone()
+ {
+ var jsonObject = new JsonObject(_duplicatePropertyNameHandling);
+
+ foreach (KeyValuePair property in _dictionary)
+ {
+ jsonObject.Add(property.Key, property.Value.Clone());
+ }
+
+ return jsonObject;
+ }
+
+ ///
+ /// Returns
+ ///
+ public override JsonValueKind ValueKind { get => JsonValueKind.Object; }
}
}
diff --git a/src/System.Text.Json/src/System/Text/Json/Node/JsonObjectEnumerator.cs b/src/System.Text.Json/src/System/Text/Json/Node/JsonObjectEnumerator.cs
index 2723e21ccc3d..9b7a7b79acff 100644
--- a/src/System.Text.Json/src/System/Text/Json/Node/JsonObjectEnumerator.cs
+++ b/src/System.Text.Json/src/System/Text/Json/Node/JsonObjectEnumerator.cs
@@ -8,7 +8,7 @@ namespace System.Text.Json
///
public struct JsonObjectEnumerator : IEnumerator>
{
- private readonly IEnumerator> _enumerator;
+ private Dictionary.Enumerator _enumerator;
///
/// Initializes a new instance of the class supporting an interation over provided JSON object.
@@ -40,6 +40,6 @@ public struct JsonObjectEnumerator : IEnumerator>
///
/// Sets the enumerator to its initial position, which is before the first element in the JSON object.
///
- public void Reset() => _enumerator.Reset();
+ void IEnumerator.Reset() => ((IEnumerator)_enumerator).Reset();
}
}
diff --git a/src/System.Text.Json/src/System/Text/Json/Node/JsonString.cs b/src/System.Text.Json/src/System/Text/Json/Node/JsonString.cs
index bcf459c7e30b..de5538f4e78a 100644
--- a/src/System.Text.Json/src/System/Text/Json/Node/JsonString.cs
+++ b/src/System.Text.Json/src/System/Text/Json/Node/JsonString.cs
@@ -2,6 +2,8 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Globalization;
+
namespace System.Text.Json
{
///
@@ -35,19 +37,25 @@ public sealed class JsonString : JsonNode, IEquatable
/// Initializes a new instance of the with a string representation of the structure.
///
/// The value to represent as a JSON string.
- public JsonString(Guid value) => Value = value.ToString();
+ public JsonString(Guid value) => Value = value.ToString("D");
///
- /// Initializes a new instance of the with a string representation of the structure.
+ /// Initializes a new instance of the with an ISO 8601 representation of the structure.
///
/// The value to represent as a JSON string.
- public JsonString(DateTime value) => Value = value.ToString();
+ ///
+ /// The date and time is outside the range of dates supported by the calendar used by the invariant culture.
+ ///
+ public JsonString(DateTime value) => Value = value.ToString("s", CultureInfo.InvariantCulture);
///
- /// Initializes a new instance of the with a string representation of the structure.
+ /// Initializes a new instance of the with an ISO 8601 representation of the structure.
///
/// The value to represent as a JSON string.
- public JsonString(DateTimeOffset value) => Value = value.ToString();
+ ///
+ /// The date and time is outside the range of dates supported by the calendar used by the invariant culture.
+ ///
+ public JsonString(DateTimeOffset value) => Value = value.ToString("s", CultureInfo.InvariantCulture);
///
/// Gets or sets the text value represented by the instance.
@@ -67,6 +75,70 @@ public string Value
/// The value represented by this instance.
public override string ToString() => _value;
+ ///
+ /// Converts the ISO 8601 text value of this instance to its equivalent.
+ ///
+ /// A equivalent to the text stored by this instance.
+ ///
+ /// Text value of this instance is not in an ISO 8601 defined DateTime format.
+ ///
+ public DateTime GetDateTime() => DateTime.ParseExact(_value, "s", CultureInfo.InvariantCulture);
+
+ ///
+ /// Converts the ISO 8601 text value of this instance to equivalent.
+ ///
+ /// A equivalent to the text stored by this instance.
+ ///
+ /// Text value of this instance is not in an ISO 8601 defined DateTimeOffset format.
+ ///
+ public DateTimeOffset GetDateTimeOffset() => DateTimeOffset.ParseExact(_value, "s", CultureInfo.InvariantCulture);
+
+ ///
+ /// Converts the text value of this instance to its equivalent.
+ ///
+ /// A equivalent to the text stored by this instance.
+ ///
+ /// Text value of this instance is not in a GUID recognized format.
+ ///
+ public Guid GetGuid() => Guid.ParseExact(_value, "D");
+
+ ///
+ /// Converts the ISO 8601 text value of this instance to its ISO 8601 equivalent.
+ /// A return value indicates whether the conversion succeeded.
+ ///
+ ///
+ /// When this method returns, contains the see cref="DateTime"/> value equivalent of the text contained in this instance,
+ /// if the conversion succeeded, or zero if the conversion failed.
+ ///
+ ///
+ /// if instance was converted successfully;
+ /// otherwise,
+ ///
+ public bool TryGetDateTime(out DateTime value) => DateTime.TryParseExact(_value, "s", CultureInfo.InvariantCulture, DateTimeStyles.None, out value);
+
+ ///
+ /// Converts the ISO 8601 text value of this instance to its equivalent.
+ /// A return value indicates whether the conversion succeeded.
+ ///
+ ///
+ /// When this method returns, contains the value equivalent of the text contained in this instance,
+ /// if the conversion succeeded, or zero if the conversion failed.
+ ///
+ ///
+ /// if instance was converted successfully;
+ /// otherwise,
+ ///
+ public bool TryGetDateTimeOffset(out DateTimeOffset value) => DateTimeOffset.TryParseExact(_value, "s", CultureInfo.InvariantCulture, DateTimeStyles.None, out value);
+
+ ///
+ /// Converts the text value of this instance to its equivalent.
+ ///
+ /// A equivalent to the text stored by this instance.
+ ///
+ /// Text value of this instance is not in a GUID recognized format.
+ ///
+ public bool TryGetGuid(out Guid value) => Guid.TryParseExact(_value, "D", out value);
+
///
/// Converts a to a .
///
@@ -131,5 +203,16 @@ public string Value
/// otherwise.
///
public static bool operator !=(JsonString left, JsonString right) => !(left == right);
+
+ ///
+ /// Creates a new JSON string that is a copy of the current instance.
+ ///
+ /// A new JSON string that is a copy of this instance.
+ public override JsonNode Clone() => new JsonString(Value);
+
+ ///
+ /// Returns
+ ///
+ public override JsonValueKind ValueKind { get => JsonValueKind.String; }
}
}
diff --git a/src/System.Text.Json/src/System/Text/Json/ThrowHelper.cs b/src/System.Text.Json/src/System/Text/Json/ThrowHelper.cs
index cbab677acbb5..00a9f47093a5 100644
--- a/src/System.Text.Json/src/System/Text/Json/ThrowHelper.cs
+++ b/src/System.Text.Json/src/System/Text/Json/ThrowHelper.cs
@@ -231,17 +231,33 @@ internal static InvalidOperationException GetJsonElementWrongTypeException(
JsonTokenType expectedType,
JsonTokenType actualType)
{
- return GetInvalidOperationException(
- SR.Format(SR.JsonElementHasWrongType, expectedType.ToValueKind(), actualType.ToValueKind()));
+ return GetJsonElementWrongTypeException(expectedType.ToValueKind(), actualType.ToValueKind());
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static InvalidOperationException GetJsonElementWrongTypeException(
string expectedTypeName,
JsonTokenType actualType)
+ {
+ return GetJsonElementWrongTypeException(expectedTypeName, actualType.ToValueKind());
+ }
+
+ [MethodImpl(MethodImplOptions.NoInlining)]
+ internal static InvalidOperationException GetJsonElementWrongTypeException(
+ JsonValueKind expectedType,
+ JsonValueKind actualType)
+ {
+ return GetInvalidOperationException(
+ SR.Format(SR.JsonElementHasWrongType, expectedType, actualType));
+ }
+
+ [MethodImpl(MethodImplOptions.NoInlining)]
+ internal static InvalidOperationException GetJsonElementWrongTypeException(
+ string expectedTypeName,
+ JsonValueKind actualType)
{
return GetInvalidOperationException(
- SR.Format(SR.JsonElementHasWrongType, expectedTypeName, actualType.ToValueKind()));
+ SR.Format(SR.JsonElementHasWrongType, expectedTypeName, actualType));
}
public static void ThrowJsonReaderException(ref Utf8JsonReader json, ExceptionResource resource, byte nextByte = default, ReadOnlySpan bytes = default)
diff --git a/src/System.Text.Json/tests/JsonArrayTests.cs b/src/System.Text.Json/tests/JsonArrayTests.cs
new file mode 100644
index 000000000000..89ff9b6b9a04
--- /dev/null
+++ b/src/System.Text.Json/tests/JsonArrayTests.cs
@@ -0,0 +1,366 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Collections.Generic;
+using System.Linq;
+using Xunit;
+
+namespace System.Text.Json.Tests
+{
+ public static class JsonArrayTests
+ {
+
+ private static void TestArray(T value1, T value2, Func getter, Func nodeCtor)
+ {
+ var value1Casted = value1 as dynamic;
+ var value2Casted = value2 as dynamic;
+
+ JsonNode value1Node = nodeCtor(value1);
+ JsonNode value2Node = nodeCtor(value2);
+
+ var list = new List() { value1 };
+ JsonArray jsonArray = new JsonArray(list as dynamic);
+ Assert.Equal(1, jsonArray.Count);
+
+ Assert.True(jsonArray.Contains(value1Node));
+ Assert.Equal(value1, getter(jsonArray));
+
+ jsonArray.Insert(0, value2 as dynamic);
+ Assert.Equal(2, jsonArray.Count);
+ Assert.True(jsonArray.Contains(value2Node));
+ Assert.Equal(value2, getter(jsonArray));
+
+ Assert.Equal(1, jsonArray.IndexOf(value1Node));
+ Assert.Equal(1, jsonArray.LastIndexOf(value1Node));
+
+ jsonArray.RemoveAt(0);
+ Assert.False(jsonArray.Contains(value2Node));
+
+ jsonArray.Remove(value1Node);
+ Assert.False(jsonArray.Contains(value1Node));
+
+ Assert.Equal(0, jsonArray.Count);
+
+ jsonArray.Add(value2Casted);
+ Assert.Equal(1, jsonArray.Count);
+ Assert.True(jsonArray.Contains(value2Node));
+ Assert.Equal(value2, getter(jsonArray));
+
+ jsonArray[0] = value1Node;
+ Assert.Equal(1, jsonArray.Count);
+ Assert.True(jsonArray.Contains(value1Node));
+ Assert.Equal(value1, getter(jsonArray));
+ }
+
+ [Fact]
+ public static void TestStringArray()
+ {
+ TestArray(
+ "value1", "value2",
+ jsonArray => ((JsonString)jsonArray[0]).Value,
+ v => new JsonString(v)
+ );
+ }
+
+ [Fact]
+ public static void TestBooleanArray()
+ {
+ TestArray(
+ true, false,
+ jsonArray => ((JsonBoolean)jsonArray[0]).Value,
+ v => new JsonBoolean(v)
+ );
+ }
+
+ [Fact]
+ public static void TestByteArray()
+ {
+ TestArray(
+ byte.MaxValue, byte.MaxValue - 1,
+ jsonArray => ((JsonNumber)jsonArray[0]).GetByte(),
+ v => new JsonNumber(v)
+ );
+ }
+
+ [Fact]
+ public static void TestInt16Array()
+ {
+ TestArray(
+ short.MaxValue, short.MaxValue - 1,
+ jsonArray => ((JsonNumber)jsonArray[0]).GetInt16(),
+ v => new JsonNumber(v)
+ );
+ }
+
+ [Fact]
+ public static void TestInt32rray()
+ {
+ TestArray(
+ int.MaxValue, int.MaxValue - 1,
+ jsonArray => ((JsonNumber)jsonArray[0]).GetInt32(),
+ v => new JsonNumber(v)
+ );
+ }
+
+ [Fact]
+ public static void TestInt64rray()
+ {
+ TestArray(
+ long.MaxValue, long.MaxValue - 1,
+ jsonArray => ((JsonNumber)jsonArray[0]).GetInt64(),
+ v => new JsonNumber(v)
+ );
+ }
+
+ [Fact]
+ public static void TestSingleArray()
+ {
+ TestArray(
+ 3.14f, 1.41f,
+ jsonArray => ((JsonNumber)jsonArray[0]).GetSingle(),
+ v => new JsonNumber(v)
+ );
+ }
+
+ [Fact]
+ public static void TestDoubleArray()
+ {
+ TestArray(
+ 3.14, 1.41,
+ jsonArray => ((JsonNumber)jsonArray[0]).GetDouble(),
+ v => new JsonNumber(v)
+ );
+ }
+
+ [Fact]
+ public static void TestSByteArray()
+ {
+ TestArray(
+ sbyte.MaxValue, sbyte.MaxValue - 1,
+ jsonArray => ((JsonNumber)jsonArray[0]).GetSByte(),
+ v => new JsonNumber(v)
+ );
+ }
+
+ [Fact]
+ public static void TestUInt16Array()
+ {
+ TestArray(
+ ushort.MaxValue, ushort.MaxValue - 1,
+ jsonArray => ((JsonNumber)jsonArray[0]).GetUInt16(),
+ v => new JsonNumber(v)
+ );
+ }
+
+ [Fact]
+ public static void TestUInt32Array()
+ {
+ TestArray(
+ uint.MaxValue, uint.MaxValue - 1,
+ jsonArray => ((JsonNumber)jsonArray[0]).GetUInt32(),
+ v => new JsonNumber(v)
+ );
+ }
+
+ [Fact]
+ public static void TestUInt64Array()
+ {
+ TestArray(
+ ulong.MaxValue, ulong.MaxValue - 1,
+ jsonArray => ((JsonNumber)jsonArray[0]).GetUInt64(),
+ v => new JsonNumber(v)
+ );
+ }
+
+ [Fact]
+ public static void TestDecimalArray()
+ {
+ TestArray(
+ decimal.One, decimal.Zero,
+ jsonArray => ((JsonNumber)jsonArray[0]).GetDecimal(),
+ v => new JsonNumber(v)
+ );
+ }
+
+ [Fact]
+ public static void TestCreatingJsonArrayFromStringArray()
+ {
+ string[] expected = { "sushi", "pasta", "cucumber soup" };
+
+ var dishesJsonArray = new JsonArray(expected);
+ Assert.Equal(3, dishesJsonArray.Count);
+
+ for (int i = 0; i < dishesJsonArray.Count; i++)
+ {
+ Assert.IsType(dishesJsonArray[i]);
+ Assert.Equal(expected[i], dishesJsonArray[i] as JsonString);
+ }
+ }
+
+ [Fact]
+ public static void TestCreatingNestedJsonArray()
+ {
+ var vertices = new JsonArray()
+ {
+ new JsonArray
+ {
+ new JsonArray
+ {
+ new JsonArray { 0, 0, 0 },
+ new JsonArray { 0, 0, 1 }
+ },
+ new JsonArray
+ {
+ new JsonArray { 0, 1, 0 },
+ new JsonArray { 0, 1, 1 }
+ }
+ },
+ new JsonArray
+ {
+ new JsonArray
+ {
+ new JsonArray { 1, 0, 0 },
+ new JsonArray { 1, 0, 1 }
+ },
+ new JsonArray
+ {
+ new JsonArray { 1, 1, 0 },
+ new JsonArray { 1, 1, 1 }
+ }
+ },
+ };
+
+ var innerJsonArray = (JsonArray)vertices[0];
+ innerJsonArray = (JsonArray)innerJsonArray[0];
+ Assert.IsType(innerJsonArray[0]);
+ }
+
+ [Fact]
+ public static void TestCreatingJsonArrayFromCollection()
+ {
+ var employeesIds = new JsonArray(EmployeesDatabase.GetTenBestEmployees().Select(employee => new JsonString(employee.Key)));
+
+ JsonString prevId = new JsonString();
+ foreach (JsonNode employeeId in employeesIds)
+ {
+ var employeeIdString = (JsonString)employeeId;
+ Assert.NotEqual(prevId, employeeIdString);
+ prevId = employeeIdString;
+ }
+ }
+
+ [Fact]
+ public static void TestCreatingJsonArrayFromCollectionOfString()
+ {
+ var employeesIds = new JsonArray(EmployeesDatabase.GetTenBestEmployees().Select(employee => employee.Key));
+
+ JsonString prevId = new JsonString();
+ foreach (JsonNode employeeId in employeesIds)
+ {
+ var employeeIdString = (JsonString)employeeId;
+ Assert.NotEqual(prevId, employeeIdString);
+ prevId = employeeIdString;
+ }
+ }
+
+ [Fact]
+ public static void TestAddingToJsonArray()
+ {
+ var employeesIds = new JsonArray();
+
+ foreach (KeyValuePair employee in EmployeesDatabase.GetTenBestEmployees())
+ {
+ employeesIds.Add(employee.Key);
+ }
+
+ JsonString prevId = new JsonString();
+ foreach (JsonNode employeeId in employeesIds)
+ {
+ var employeeIdString = (JsonString)employeeId;
+ Assert.NotEqual(prevId, employeeIdString);
+ prevId = employeeIdString;
+ }
+ }
+
+ [Fact]
+ public static void TestAccesingNestedJsonArrayGetPropertyMethod()
+ {
+ var issues = new JsonObject()
+ {
+ { "features", new JsonString [] { "new functionality 1", "new functionality 2" } },
+ { "bugs", new JsonString [] { "bug 123", "bug 4566", "bug 821" } },
+ { "tests", new JsonString [] { "code coverage" } },
+ };
+
+ issues.GetJsonArrayPropertyValue("bugs").Add("bug 12356");
+ ((JsonString)issues.GetJsonArrayPropertyValue("features")[0]).Value = "feature 1569";
+ ((JsonString)issues.GetJsonArrayPropertyValue("features")[1]).Value = "feature 56134";
+
+ Assert.Equal((JsonString)"bug 12356", ((JsonArray)issues["bugs"])[3]);
+ Assert.Equal("feature 1569", (JsonString)((JsonArray)issues["features"])[0]);
+ Assert.Equal("feature 56134", (JsonString)((JsonArray)issues["features"])[1]);
+ }
+
+ [Fact]
+ public static void TestAccesingNestedJsonArrayTryGetPropertyMethod()
+ {
+ var issues = new JsonObject()
+ {
+ { "features", new JsonString [] { "new functionality 1", "new functionality 2" } },
+ };
+
+ Assert.True(issues.TryGetJsonArrayPropertyValue("features", out JsonArray featuresArray));
+ Assert.Equal("new functionality 1", (JsonString)featuresArray[0]);
+ Assert.Equal("new functionality 2", (JsonString)featuresArray[1]);
+ }
+
+ [Fact]
+ public static void TestOutOfRangeException()
+ {
+ Assert.Throws(() => new JsonArray()[-1]);
+ Assert.Throws(() => new JsonArray()[-1] = new JsonString());
+ Assert.Throws(() => new JsonArray()[0]);
+ Assert.Throws(() => new JsonArray()[0] = new JsonString());
+ Assert.Throws(() => new JsonArray()[1]);
+ Assert.Throws(() => new JsonArray()[1] = new JsonString());
+ }
+
+ [Fact]
+ public static void TestIsReadOnly()
+ {
+ Assert.False(new JsonArray().IsReadOnly);
+ }
+
+ [Fact]
+ public static void TestClean()
+ {
+ var jsonArray = new JsonArray { 1, 2, 3 };
+
+ Assert.Equal(3, jsonArray.Count);
+ Assert.Equal((JsonNumber)1, jsonArray[0]);
+ Assert.Equal((JsonNumber)2, jsonArray[1]);
+ Assert.Equal((JsonNumber)3, jsonArray[2]);
+
+ jsonArray.Clear();
+
+ Assert.Equal(0, jsonArray.Count);
+ }
+
+ [Fact]
+ public static void TestRemoveAll()
+ {
+ var jsonArray = new JsonArray { 1, 2, 3 };
+
+ Assert.Equal(3, jsonArray.Count);
+ Assert.Equal((JsonNumber)1, jsonArray[0]);
+ Assert.Equal((JsonNumber)2, jsonArray[1]);
+ Assert.Equal((JsonNumber)3, jsonArray[2]);
+
+ jsonArray.RemoveAll(v => ((JsonNumber)v).GetInt32() <= 2);
+
+ Assert.Equal(1, jsonArray.Count);
+ Assert.Equal((JsonNumber)3, jsonArray[0]);
+ }
+ }
+}
diff --git a/src/System.Text.Json/tests/JsonNodeCloneTests.cs b/src/System.Text.Json/tests/JsonNodeCloneTests.cs
new file mode 100644
index 000000000000..6ed89ed8da1f
--- /dev/null
+++ b/src/System.Text.Json/tests/JsonNodeCloneTests.cs
@@ -0,0 +1,59 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using Xunit;
+
+namespace System.Text.Json.Tests
+{
+ public static class JsonNodeCloneTests
+ {
+ [Fact]
+ public static void TestCloneJsonArray()
+ {
+ var jsonArray = new JsonArray { "value1", "value2" };
+ var jsonArrayCopy = jsonArray.Clone() as JsonArray;
+ Assert.Equal(2, jsonArrayCopy.Count);
+ jsonArray.Add("value3");
+ Assert.Equal(2, jsonArrayCopy.Count);
+ }
+
+ [Fact]
+ public static void TestDeepCloneJsonArray()
+ {
+ JsonArray inner = new JsonArray { 1, 2, 3 };
+ JsonArray outer = new JsonArray { inner };
+ JsonArray outerClone = (JsonArray)outer.Clone();
+ ((JsonArray) outerClone[0]).Add(4);
+
+ Assert.Equal(3, inner.Count);
+ }
+
+ [Fact]
+ public static void TestCloneJsonNode()
+ {
+ var jsonObject = new JsonObject
+ {
+ { "text", "property value" },
+ { "boolean", true },
+ { "number", 15 },
+ { "array", new JsonString[] { "value1", "value2"} }
+ };
+
+ var jsonObjectCopy = (JsonObject)jsonObject.Clone();
+
+ jsonObject["text"] = (JsonString)"something different";
+ Assert.Equal("property value", (JsonString)jsonObjectCopy["text"]);
+
+ ((JsonBoolean)jsonObject["boolean"]).Value = false;
+ Assert.True(((JsonBoolean)jsonObjectCopy["boolean"]).Value);
+
+ Assert.Equal(2, jsonObjectCopy.GetJsonArrayPropertyValue("array").Count);
+ jsonObject.GetJsonArrayPropertyValue("array").Add("value3");
+ Assert.Equal(2, jsonObjectCopy.GetJsonArrayPropertyValue("array").Count);
+
+ jsonObject.Add("new one", 123);
+ Assert.Equal(4, jsonObjectCopy.PropertyNames.Count);
+ }
+ }
+}
diff --git a/src/System.Text.Json/tests/JsonNodeParseTests.cs b/src/System.Text.Json/tests/JsonNodeParseTests.cs
new file mode 100644
index 000000000000..426772ee7bb9
--- /dev/null
+++ b/src/System.Text.Json/tests/JsonNodeParseTests.cs
@@ -0,0 +1,55 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using Xunit;
+
+namespace System.Text.Json.Tests
+{
+ public static class JsonNodeParseTests
+ {
+ private static string jsonSampleString = @"
+ {
+ ""text"": ""property value"",
+ ""boolean true"": true,
+ ""boolean false"": false,
+ ""null"": null,
+ ""int"": 17,
+ ""double"": 3.14,
+ ""scientific"": 3e100,
+ ""array"" : [1,2,3],
+ ""inner object"" :
+ {
+ ""inner property"" : ""value""
+ }
+ }";
+
+ [Fact]
+ public static void TestParseStringToJsonNode()
+ {
+ JsonNode node = JsonNode.Parse(jsonSampleString);
+
+ var jsonObject = (JsonObject)node;
+ Assert.Equal(9, jsonObject.PropertyNames.Count);
+ Assert.Equal(9, jsonObject.PropertyValues.Count);
+ Assert.Equal("property value", (JsonString)jsonObject["text"]);
+ Assert.True(((JsonBoolean)jsonObject["boolean true"]).Value);
+ Assert.False(((JsonBoolean)jsonObject["boolean false"]).Value);
+ Assert.Null(jsonObject["null"]);
+ Assert.Equal(17, ((JsonNumber)jsonObject["int"]).GetInt32());
+ Assert.Equal(3.14, ((JsonNumber)jsonObject["double"]).GetDouble());
+ Assert.Equal("3e100", ((JsonNumber)jsonObject["scientific"]).ToString());
+
+ var innerArray = (JsonArray)jsonObject["array"];
+ Assert.Equal(3, innerArray.Count);
+ Assert.Equal(1, ((JsonNumber)innerArray[0]).GetInt32());
+ Assert.Equal(2, ((JsonNumber)innerArray[1]).GetInt32());
+ Assert.Equal(3, ((JsonNumber)innerArray[2]).GetInt32());
+
+ var innerObject = (JsonObject)jsonObject["inner object"];
+ Assert.Equal(1, innerObject.PropertyNames.Count);
+ Assert.Equal(1, innerObject.PropertyValues.Count);
+ Assert.Equal("value", (JsonString)innerObject["inner property"]);
+ }
+ }
+}
diff --git a/src/System.Text.Json/tests/JsonNodeTestData.cs b/src/System.Text.Json/tests/JsonNodeTestData.cs
new file mode 100644
index 000000000000..39d443c2f7c0
--- /dev/null
+++ b/src/System.Text.Json/tests/JsonNodeTestData.cs
@@ -0,0 +1,111 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Collections.Generic;
+
+namespace System.Text.Json.Tests
+{
+ ///
+ /// Helper class simulating external library
+ ///
+ internal static class EmployeesDatabase
+ {
+ private static int s_id = 0;
+ public static KeyValuePair GetNextEmployee()
+ {
+ var employee = new JsonObject()
+ {
+ { "name", "John" } ,
+ { "surname", "Smith"},
+ { "age", 45 }
+ };
+
+ return new KeyValuePair("employee" + s_id++, employee);
+ }
+
+ public static IEnumerable> GetTenBestEmployees()
+ {
+ for (int i = 0; i < 10; i++)
+ yield return GetNextEmployee();
+ }
+
+ ///
+ /// Returns following JsonObject:
+ /// {
+ /// { "name" : "John" }
+ /// { "phone numbers" : { "work" : "425-555-0123", "home": "425-555-0134" } }
+ /// {
+ /// "reporting employees" :
+ /// {
+ /// "software developers" :
+ /// {
+ /// "full time employees" : /JsonObject of 3 employees fromk database/
+ /// "intern employees" : /JsonObject of 2 employees fromk database/
+ /// },
+ /// "HR" : /JsonObject of 10 employees fromk database/
+ /// }
+ ///
+ ///
+ public static JsonObject GetManager()
+ {
+ var manager = GetNextEmployee().Value as JsonObject;
+
+ manager.Add
+ (
+ "phone numbers",
+ new JsonObject()
+ {
+ { "work", "425-555-0123" }, { "home", "425-555-0134" }
+ }
+ );
+
+ manager.Add
+ (
+ "reporting employees", new JsonObject()
+ {
+ {
+ "software developers", new JsonObject()
+ {
+ {
+ "full time employees", new JsonObject()
+ {
+ EmployeesDatabase.GetNextEmployee(),
+ EmployeesDatabase.GetNextEmployee(),
+ EmployeesDatabase.GetNextEmployee(),
+ }
+ },
+ {
+ "intern employees", new JsonObject()
+ {
+ EmployeesDatabase.GetNextEmployee(),
+ EmployeesDatabase.GetNextEmployee(),
+ }
+ }
+ }
+ },
+ {
+ "HR", new JsonObject()
+ {
+ {
+ "full time employees", new JsonObject(EmployeesDatabase.GetTenBestEmployees())
+ }
+ }
+ }
+ }
+ );
+
+ return manager;
+ }
+ }
+
+ ///
+ /// Helper class simulating enum
+ ///
+ internal enum AvailableStateCodes
+ {
+ WA,
+ CA,
+ NY,
+ }
+}
diff --git a/src/System.Text.Json/tests/JsonNodeToJsonElementTests.cs b/src/System.Text.Json/tests/JsonNodeToJsonElementTests.cs
new file mode 100644
index 000000000000..dc222e4aa6e6
--- /dev/null
+++ b/src/System.Text.Json/tests/JsonNodeToJsonElementTests.cs
@@ -0,0 +1,112 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Collections;
+using Xunit;
+
+namespace System.Text.Json.Tests
+{
+ public static class JsonNodeToJsonElementTests
+ {
+ [Fact]
+ public static void TestAsJsonElement()
+ {
+ var jsonObject = new JsonObject
+ {
+ { "text", "property value" },
+ { "boolean", true },
+ { "number", 15 },
+ { "null node", (JsonNode) null },
+ { "array", new JsonString[] { "value1", "value2"} }
+ };
+
+ JsonElement jsonElement = jsonObject.AsJsonElement();
+ Assert.False(jsonElement.IsImmutable);
+
+ JsonElement.ObjectEnumerator enumerator = jsonElement.EnumerateObject();
+
+ enumerator.MoveNext();
+ Assert.Equal("text", enumerator.Current.Name);
+ Assert.Equal(JsonValueKind.String, enumerator.Current.Value.ValueKind);
+ Assert.Equal("property value", enumerator.Current.Value.GetString());
+
+ enumerator.MoveNext();
+ Assert.Equal("boolean", enumerator.Current.Name);
+ Assert.Equal(JsonValueKind.True, enumerator.Current.Value.ValueKind);
+ Assert.True(enumerator.Current.Value.GetBoolean());
+
+ enumerator.MoveNext();
+ Assert.Equal("number", enumerator.Current.Name);
+ Assert.Equal(15, enumerator.Current.Value.GetInt32());
+ Assert.Equal(JsonValueKind.Number, enumerator.Current.Value.ValueKind);
+
+ enumerator.MoveNext();
+ Assert.Equal("null node", enumerator.Current.Name);
+ Assert.Equal(JsonValueKind.Null, enumerator.Current.Value.ValueKind);
+
+ enumerator.MoveNext();
+ Assert.Equal("array", enumerator.Current.Name);
+ Assert.Equal(2, enumerator.Current.Value.GetArrayLength());
+ Assert.Equal(JsonValueKind.Array, enumerator.Current.Value.ValueKind);
+ JsonElement.ArrayEnumerator innerEnumerator = enumerator.Current.Value.EnumerateArray();
+
+ innerEnumerator.MoveNext();
+ Assert.Equal(JsonValueKind.String, innerEnumerator.Current.ValueKind);
+ Assert.Equal("value1", innerEnumerator.Current.GetString());
+
+ innerEnumerator.MoveNext();
+ Assert.Equal(JsonValueKind.String, innerEnumerator.Current.ValueKind);
+ Assert.Equal("value2", innerEnumerator.Current.GetString());
+
+ Assert.False(innerEnumerator.MoveNext());
+ innerEnumerator.Dispose();
+
+ Assert.False(enumerator.MoveNext());
+ enumerator.Dispose();
+
+ // Modifying JsonObject will change JsonElement:
+
+ jsonObject["text"] = new JsonNumber("123");
+ Assert.Equal(123, jsonElement.GetProperty("text").GetInt32());
+ }
+
+ [Fact]
+ public static void TestArrayIterator()
+ {
+ JsonArray array = new JsonArray { 1, 2, 3 };
+ JsonElement jsonNodeElement = array.AsJsonElement();
+ IEnumerator enumerator = jsonNodeElement.EnumerateArray();
+ array.Add(4);
+ Assert.Throws(() => enumerator.MoveNext());
+ }
+
+ [Fact]
+ public static void TestGetNode()
+ {
+ var jsonObject = new JsonObject
+ {
+ { "text", "property value" },
+ { "boolean", true },
+ { "number", 15 },
+ { "null node", (JsonNode) null },
+ { "array", new JsonString[] { "value1", "value2"} }
+ };
+
+ JsonElement jsonElement = jsonObject.AsJsonElement();
+ JsonObject jsonObjectFromElement = (JsonObject)JsonNode.GetNode(jsonElement);
+
+ Assert.Equal("property value", (JsonString)jsonObjectFromElement["text"]);
+
+ // Modifying JsonObject will change JsonObjectFromElement:
+
+ jsonObject["text"] = new JsonString("something different");
+ Assert.Equal("something different", (JsonString)jsonObjectFromElement["text"]);
+
+ // Modifying JsonObjectFromElement will change JsonObject:
+
+ ((JsonBoolean)jsonObjectFromElement["boolean"]).Value = false;
+ Assert.False(((JsonBoolean)jsonObject["boolean"]).Value);
+ }
+ }
+}
diff --git a/src/System.Text.Json/tests/JsonObjectTests.TestData.cs b/src/System.Text.Json/tests/JsonObjectTests.TestData.cs
deleted file mode 100644
index fb324ed49400..000000000000
--- a/src/System.Text.Json/tests/JsonObjectTests.TestData.cs
+++ /dev/null
@@ -1,120 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System.Collections.Generic;
-
-namespace System.Text.Json.Tests
-{
- public static partial class JsonObjectTests
- {
- ///
- /// Helper class simulating external library
- ///
- private static class EmployeesDatabase
- {
- private static int s_id = 0;
- public static KeyValuePair GetNextEmployee()
- {
- var employee = new JsonObject()
- {
- { "name", "John" } ,
- { "surname", "Smith"},
- { "age", 45 }
- };
-
- return new KeyValuePair("employee" + s_id++, employee);
- }
-
- public static IEnumerable> GetTenBestEmployees()
- {
- for (int i = 0; i < 10; i++)
- yield return GetNextEmployee();
- }
-
- ///
- /// Returns following JsonObject:
- /// {
- /// { "name" : "John" }
- /// { "phone numbers" : { "work" : "123-456-7890", "home": "123-456-7890" } }
- /// {
- /// "reporting employees" :
- /// {
- /// "software developers" :
- /// {
- /// "full time employees" : /JsonObject of 3 employees fromk database/
- /// "intern employees" : /JsonObject of 2 employees fromk database/
- /// },
- /// "HR" : /JsonObject of 10 employees fromk database/
- /// }
- ///
- ///
- public static JsonObject GetManager()
- {
- var manager = GetNextEmployee().Value as JsonObject;
-
- manager.Add
- (
- "phone numbers",
- new JsonObject()
- {
- { "work", "123-456-7890" }, { "home", "123-456-7890" }
- }
- );
-
- manager.Add
- (
- "reporting employees", new JsonObject()
- {
- {
- "software developers", new JsonObject()
- {
- {
- "full time employees", new JsonObject()
- {
- EmployeesDatabase.GetNextEmployee(),
- EmployeesDatabase.GetNextEmployee(),
- EmployeesDatabase.GetNextEmployee(),
- }
- },
- {
- "intern employees", new JsonObject()
- {
- EmployeesDatabase.GetNextEmployee(),
- EmployeesDatabase.GetNextEmployee(),
- }
- }
- }
- },
- {
- "HR", new JsonObject()
- {
- {
- "full time employees", new JsonObject(EmployeesDatabase.GetTenBestEmployees())
- }
- }
- }
- }
- );
-
- return manager;
- }
- public static void PerformHeavyOperations(JsonElement employee) { }
- }
-
- private static class HealthCare
- {
- public static void CreateMedicalAppointment(string personName) { }
- }
-
- ///
- /// Helper class simulating enum
- ///
- private enum AvailableStateCodes
- {
- WA,
- CA,
- NY,
- }
- }
-}
diff --git a/src/System.Text.Json/tests/JsonObjectTests.cs b/src/System.Text.Json/tests/JsonObjectTests.cs
index 9759d05c15ca..392eaf568b6d 100644
--- a/src/System.Text.Json/tests/JsonObjectTests.cs
+++ b/src/System.Text.Json/tests/JsonObjectTests.cs
@@ -3,11 +3,13 @@
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
using Xunit;
namespace System.Text.Json.Tests
{
- public static partial class JsonObjectTests
+ public static class JsonObjectTests
{
[Fact]
public static void TestDefaultConstructor()
@@ -131,20 +133,29 @@ public static void TestGuid()
Assert.Equal(guidString, (JsonString)jsonObject["guid"]);
}
- [Fact]
- public static void TestDateTime()
+ public static IEnumerable
+
+
+
-