Skip to content
This repository was archived by the owner on Jan 23, 2023. It is now read-only.

Writable JSON API changes - #40673

Merged
kasiabulat merged 45 commits into
dotnet:masterfrom
kasiabulat:kasiabulat/writable-json-api-changes
Sep 9, 2019
Merged

kasiabulat merged 45 commits into
dotnet:masterfrom
kasiabulat:kasiabulat/writable-json-api-changes

Conversation

@kasiabulat

Copy link
Copy Markdown
Contributor

I added majority of API and implementation changes and missing functionalities, including:

  • Changing null JsonNode into JsonNull
  • Moving implicit casts operators to JsonNode
  • Rewriting JsonObject to use a combination of dictionary and linked list of properties
  • Adding my own version of Parse
  • Moving handling duplicates from JsonObject to Parse
  • Rewriting DeepCopy not to use recursion
  • Adding WriteTo(Utf8JsonWriter)
  • Adding ToJsonString using WriteTo(Utf8JsonWriter)

I am still missing adding StringComparison to 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

@kasiabulat

Copy link
Copy Markdown
Contributor Author

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 Json.Node parsing, because they have similar logic. Probably I could try to unify more the way they handle end of object/array and how they retrieve additional information from stack.

@kasiabulat

Copy link
Copy Markdown
Contributor Author

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; }

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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; }

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's consider that separately (worth noting in the doc).

@kasiabulat

Copy link
Copy Markdown
Contributor Author

Can I merge this?

@kasiabulat

Copy link
Copy Markdown
Contributor Author

In the meantime I added more tests to improve code coverage.

@kasiabulat

Copy link
Copy Markdown
Contributor Author

I added more tests and addressed new comments. Current coverage:

Name Covered Uncovered Coverable Total Line coverage Branch coverage
System.Text.Json.JsonArray 148 0 148 380 100% 100%
System.Text.Json.JsonArrayEnumerator 10 0 10 50 100%
System.Text.Json.JsonBoolean 16 0 16 103 100% 100%
System.Text.Json.JsonElement 629 13 642 2096 97.9% 94.6%
System.Text.Json.JsonNode 263 2 265 598 99.2%  99%
System.Text.Json.JsonNull 9 0 9 73 100%
System.Text.Json.JsonNumber 75 0 75 622 100%  100%
System.Text.Json.JsonObject 203 0 203 597 100%  100%
System.Text.Json.JsonObjectEnumerator 27 0 27 81 100% 100%
System.Text.Json.JsonObjectProperty 11 0 11 22 100%  
System.Text.Json.JsonString 27 0 27 212 100% 100%

Uncovered lines are either unreachable / unsupported or handling unspecified behavior. 

@ahsonkhan ahsonkhan left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
* 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.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
* `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.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
* `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`.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
* `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; }

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, probably JsonNodeOptions would be more appropriate.


[Fact]
public static void TestAddingJsonArray()
public static void TestGetJsonArrayPropertyValue()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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");

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Assert.False?

jsonObject.Remove("ENCYCLOPAEDIA", StringComparison.CurrentCulture);
Assert.Equal(4, jsonObject.Count());

Assert.True(jsonObject.ContainsProperty("ENCYCLOPAEDIA", StringComparison.InvariantCultureIgnoreCase));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How about Ordinal and OrdinalIgnoreCase?

jsonObject.Remove("ENCYCLOPAEDIA");
Assert.Equal(4, jsonObject.Count());

Assert.False(jsonObject.ContainsProperty("ENCYCLOPAEDIA", StringComparison.CurrentCulture));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).

@kasiabulat

Copy link
Copy Markdown
Contributor Author

I changed JsonReaderOptions into JsonDocumentOptions and removed unnecessary Add(string, JsonArray) overload from JsonObject, I will address other feedback in subsequent PR.

/// <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);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We didn't discuss it; yes, probably GetJsonNode would be better.

}
}

Debug.Assert(toReturn != null);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this actually a failing scenario? What happens today if I do JsonNode.DeepCopy(JsonDocument.Parse(""))

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

JsonDocument will throw JsonReaderException then.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe we should also wrap this MemoryStream inside a using statement since it is also disposable.

@kasiabulat kasiabulat Sep 11, 2019 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, but I changed it to ArrayBufferWriter anyway.

ref JsonNode toReturn,
DuplicatePropertyNameHandling duplicatePropertyNameHandling = DuplicatePropertyNameHandling.Replace)
{
if (currentNodes.Any())

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we just add some comment in here saying that currentNodes will really mean that we are inside either an object or an array?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok, I can add it.

@kasiabulat
kasiabulat merged commit 37b3739 into dotnet:master Sep 9, 2019
@kasiabulat
kasiabulat deleted the kasiabulat/writable-json-api-changes branch September 9, 2019 21:53
@kasiabulat kasiabulat mentioned this pull request Sep 11, 2019
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}");

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can test this code path as follows to improve code coverage:

        [Fact]
        public static void TestDeepCopyDefault()
        {
            JsonNode.DeepCopy(default); // Assert that this throws.
        }

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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'.

@ahsonkhan ahsonkhan added this to the 5.0 milestone Nov 12, 2019
@iSazonov

iSazonov commented Dec 6, 2019

Copy link
Copy Markdown
Contributor

Is there a nuget with the new APIs?

@ahsonkhan

ahsonkhan commented Dec 6, 2019 •

Copy link
Copy Markdown

Is there a nuget with the new APIs?

Yes, you can grab the alpha release of the System.Text.Json NuGet package from the daily feed and add it as a Package Reference to your project (as long as the project is netstandard2.0 or higher):
https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet5/nuget/v3/index.json
Version: 5.0.0-alpha.1.19563.6 (or higher)

You could also grab the nightly shared framework, if you are targeting .NET Core 5.0:
https://github.com/dotnet/runtime/blob/4f9ae42d861fcb4be2fcd5d3d55d5f227d30e723/docs/project/dogfooding.md#install-prerequisites

picenka21 pushed a commit to picenka21/runtime that referenced this pull request Feb 18, 2022
* 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
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants