Repository navigation
Writable JSON API changes - #40673
Conversation
|
I am not sure if naming and organization of files is OK. I wanted to join all of the methods performing JSON element/node/string traversal into |
|
Of course I hoped everything will work on netfx, I will fix failure when applying review feedback. |
| 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 implicit operator System.Text.Json.JsonNode (bool value) { throw null; } |
There was a problem hiding this comment.
What about nullable types?
bool? nullableBool = true;
JsonToken token = nullableBool;Should have implicit operator for all structs:
public static implicit operator System.Text.Json.JsonNode (bool? value) { throw null; }There was a problem hiding this comment.
Let's consider that separately (worth noting in the doc).
|
Can I merge this? |
|
In the meantime I added more tests to improve code coverage. |
|
I added more tests and addressed new comments. Current coverage:
Uncovered lines are either unreachable / unsupported or handling unspecified behavior. |
ahsonkhan
left a comment
There was a problem hiding this comment.
Some feedback, mostly nits and questions.
| * No additional overloads of Add methods for primary types (bool, string, int, double, long...) for `JsonObject` and `JsonArray`. Instead - implicit cast operators in JsonNode. | ||
| * `Sort` not implemented for `JsonArray`, beacuse there is no right way to compare `JsonObjects`. If a user wants to sort a `JsonArray` of `JsonNumbers`, `JsonBooleans` or `JsonStrings` they now needs to do the following: convert the `JsonArray` to a regular array (by iterating through all elements), call sort (and convert back to `JsonArray` if needed). | ||
| * No support for duplicates of property names. Possibly, adding an option for the user to choose from: "first value", "last value", or throw-on-duplicate. | ||
| * Property names duplicates handling method possible to chose during parsing to `JsonNode`. When creating `JsonObject` Add method throws an exception for duplicates and indexer replaces old property value with new one. |
There was a problem hiding this comment.
| * Property names duplicates handling method possible to chose during parsing to `JsonNode`. When creating `JsonObject` Add method throws an exception for duplicates and indexer replaces old property value with new one. | |
| * Property names duplicates handling method possible to choose during parsing to `JsonNode`. When creating `JsonObject` Add method throws an exception for duplicates and indexer replaces old property value with new one. |
| * `DeepCopy` method allowing to change JsonElement into JsonNode recursively transforming all of the elements. | ||
| * `AsJsonElement`method allowing to change JsonNode into JsonElement with IsImmutable property set to false. | ||
| * `IsImmutable` property informing if JsonElement is keeping JsonDocument or JsonNode underneath. | ||
| * `Parse(string)` method to be able to parse a JSON string right into JsonNode if the user knows they wants mutable version. It allows chosing duplicates handling method. |
There was a problem hiding this comment.
| * `Parse(string)` method to be able to parse a JSON string right into JsonNode if the user knows they wants mutable version. It allows chosing duplicates handling method. | |
| * `Parse(string)` method to be able to parse a JSON string right into JsonNode if the user knows they want a mutable version. It allows choosing duplicates handling method. |
| * `IsImmutable` property informing if JsonElement is keeping JsonDocument or JsonNode underneath. | ||
| * `Parse(string)` method to be able to parse a JSON string right into JsonNode if the user knows they wants mutable version. It allows chosing duplicates handling method. | ||
| * `Clone` method to make a copy of the whole JsonNode tree. | ||
| * `GetNode` and TryGetNode methods allowing to retrieve it from JsonElement. |
There was a problem hiding this comment.
| * `GetNode` and TryGetNode methods allowing to retrieve it from JsonElement. | |
| * `GetNode` and `TryGetNode` methods allowing to retrieve it from JsonElement. |
| * Internal `WriteTo(Utf8JsonWriter)` method for writing a JsonNode to a Utf8JsonWriter without having to go through JsonElement. | ||
| * `ToJsonString` method transforming JsonNode to string representation using WriteTo. | ||
| * No recursive equals for `JsonArray` and `JsonObject`. | ||
| * `JsonNode` derived types does not implement `IComparable`. |
There was a problem hiding this comment.
| * `JsonNode` derived types does not implement `IComparable`. | |
| * `JsonNode` derived types do not implement `IComparable`. |
| public static implicit operator System.Text.Json.JsonNode (uint value) { throw null; } | ||
| [System.CLSCompliantAttribute(false)] | ||
| public static implicit operator System.Text.Json.JsonNode (ulong value) { throw null; } | ||
| public static System.Text.Json.JsonNode Parse(string json, System.Text.Json.JsonReaderOptions options = default(System.Text.Json.JsonReaderOptions), System.Text.Json.DuplicatePropertyNameHandling duplicatePropertyNameHandling = System.Text.Json.DuplicatePropertyNameHandling.Replace) { throw null; } |
There was a problem hiding this comment.
I believe this should take JsonDocumentOptions and maybe we add DuplicatePropertyNameHandling to it instead of a separate option being passed in (we can defer this change to a subequent PR).
There was a problem hiding this comment.
Ok, for now I changed it JsonReaderOptions into JsonDocumentOptions. I am not sure if we should add DuplicatePropertyNameHandling to JsonDocumentOptions, because JsonDocument does not support it, so users will be confused by seeing that setting this option does not change anything it this case.
There was a problem hiding this comment.
I think it's fine for JsonDocumentOptions to throw something like ArgumentException while we don't have support for DuplicatePropertyNameHandling. Having a separate option being passed-in doesn't scale well. If we want to add a new option that is specific to JsonNode/JsonDocument, would we then add a new Parse overload?
Also, we can re-visit this if JsonDocument cannot support the various DuplicatePropertyNameHandling modes, and maybe create a JsonNodeOptions struct that is similar to JsonReaderOptions/JsonDocumentOptions, but with the extra option for duplicates.
There was a problem hiding this comment.
Yes, probably JsonNodeOptions would be more appropriate.
|
|
||
| [Fact] | ||
| public static void TestAddingJsonArray() | ||
| public static void TestGetJsonArrayPropertyValue() |
There was a problem hiding this comment.
Add a test where the property being searched for is in a nested object (and that it doesn't find it), i.e. these APIs only search within the current object level.
|
|
||
| Assert.False(jsonObject.ContainsProperty("ENCYCLOPAEDIA")); | ||
| Assert.False(jsonObject.TryGetPropertyValue("ENCYCLOPAEDIA", out JsonNode jsonNode)); | ||
| Assert.Null(jsonNode); |
There was a problem hiding this comment.
Question: Do we have a test where the property we are searching for has the value "null" so TryGet returns true and JsonNode is not null, but rather is a JsonNull? If so, great. Otherwise, let's add it.
There was a problem hiding this comment.
We have such test for indexer, I can add it for Get/(Try)Get as well.
| Assert.False(jsonObject.TryGetPropertyValue("ENCYCLOPAEDIA", out JsonNode jsonNode)); | ||
| Assert.Null(jsonNode); | ||
| Assert.Throws<KeyNotFoundException>(() => jsonObject.GetPropertyValue("ENCYCLOPAEDIA")); | ||
| jsonObject.Remove("ENCYCLOPAEDIA"); |
| jsonObject.Remove("ENCYCLOPAEDIA", StringComparison.CurrentCulture); | ||
| Assert.Equal(4, jsonObject.Count()); | ||
|
|
||
| Assert.True(jsonObject.ContainsProperty("ENCYCLOPAEDIA", StringComparison.InvariantCultureIgnoreCase)); |
There was a problem hiding this comment.
How about Ordinal and OrdinalIgnoreCase?
| jsonObject.Remove("ENCYCLOPAEDIA"); | ||
| Assert.Equal(4, jsonObject.Count()); | ||
|
|
||
| Assert.False(jsonObject.ContainsProperty("ENCYCLOPAEDIA", StringComparison.CurrentCulture)); |
There was a problem hiding this comment.
We should add tests where we set the current culture to something else and then check both cases (using StringComparison.CurrentCulture finds what we are looking for because now it matches, and one where because we use currentculture, it doesn't).
|
I changed |
| /// <exception cref="ArgumentException"> | ||
| /// Provided <see cref="JsonElement"/> was not build from <see cref="JsonNode"/>. | ||
| /// </exception> | ||
| public static JsonNode GetNode(JsonElement jsonElement) => !jsonElement.IsImmutable ? (JsonNode)jsonElement._parent : throw new ArgumentException(SR.NotNodeJsonElementParent); |
There was a problem hiding this comment.
Did we ever discussed why is this one called GetNode and not GetJsonNode? Giving the full name of the return type would be better in my opinion.
There was a problem hiding this comment.
We didn't discuss it; yes, probably GetJsonNode would be better.
| } | ||
| } | ||
|
|
||
| Debug.Assert(toReturn != null); |
There was a problem hiding this comment.
Is this actually a failing scenario? What happens today if I do JsonNode.DeepCopy(JsonDocument.Parse(""))
There was a problem hiding this comment.
JsonDocument will throw JsonReaderException then.
There was a problem hiding this comment.
For context, empty JSON is invalid (which is why JsonDocument fails to parse it).
| /// <returns>JSON representation of current instance.</returns> | ||
| public string ToJsonString() | ||
| { | ||
| var stream = new MemoryStream(); |
There was a problem hiding this comment.
I believe we should also wrap this MemoryStream inside a using statement since it is also disposable.
There was a problem hiding this comment.
Thanks, but I changed it to ArrayBufferWriter anyway.
| ref JsonNode toReturn, | ||
| DuplicatePropertyNameHandling duplicatePropertyNameHandling = DuplicatePropertyNameHandling.Replace) | ||
| { | ||
| if (currentNodes.Any()) |
There was a problem hiding this comment.
Can we just add some comment in here saying that currentNodes will really mean that we are inside either an object or an array?
There was a problem hiding this comment.
Ok, I can add it.
| AddToParent(new KeyValuePair<string, JsonNode>(currentPair.Key, jsonNull), ref currentNodes, ref toReturn); | ||
| break; | ||
| default: | ||
| Debug.Assert(jsonElement.ValueKind == JsonValueKind.Undefined, "No handler for JsonValueKind.{jsonElement.ValueKind}"); |
There was a problem hiding this comment.
You can test this code path as follows to improve code coverage:
[Fact]
public static void TestDeepCopyDefault()
{
JsonNode.DeepCopy(default); // Assert that this throws.
}There was a problem hiding this comment.
Btw, the error message in that case could use some work:
System.InvalidOperationException : The requested operation requires an element of type 'Undefined', but the target element has type 'Undefined'.
|
Is there a nuget with the new APIs? |
Yes, you can grab the alpha release of the You could also grab the nightly shared framework, if you are targeting .NET Core 5.0: |
* implicit operators moved to JsonNode * JsonNull introduced * JsonObject rewritten to use JsonObjectProperty * JsonElement.ObjectEnumerator changed to use _current instead of _enumerator * iterative DeepCopy implemented * code reorganized * parse implemented * JsonDocumentOptions added to JsonNode.Parse * WriteTo and ToJsonString added * specification adjusted * string comparison added * JsosReadonlyDomWriteTests reused * code coverage improved * minor other fixes * review comments included Commit migrated from dotnet/corefx@37b3739
I added majority of API and implementation changes and missing functionalities, including:
JsonNodeintoJsonNullJsonNodeJsonObjectto use a combination of dictionary and linked list of propertiesParseJsonObjecttoParseDeepCopynot to use recursionWriteTo(Utf8JsonWriter)ToJsonStringusingWriteTo(Utf8JsonWriter)I am still missing adding
StringComparisonto methods looking up properties. I didn't change the naming (to include "tree" prefix) for now. And I need to add much more tests, especially testing new features.addresses: #39922
cc: @bartonjs @ahsonkhan @ericstj @joperezr @terrajobst @JamesNK @stephentoub