static void FromDiffExample() { using var sourceDoc = JsonDocument.Parse(@" { ""title"": ""Goodbye!"", ""author"" : { ""givenName"" : ""John"", ""familyName"" : ""Doe"" }, ""tags"":[ ""example"", ""sample"" ], ""content"": ""This will be unchanged"" } "); using var targetDoc = JsonDocument.Parse(@" { ""title"": ""Hello!"", ""author"": { ""givenName"": ""John"" }, ""tags"": [ ""example"" ], ""content"": ""This will be unchanged"", ""phoneNumber"": ""\u002B01-123-456-7890"" } "); using JsonDocument patch = JsonMergePatch.FromDiff(sourceDoc.RootElement, targetDoc.RootElement); var options = new JsonSerializerOptions() { WriteIndented = true }; Console.WriteLine("The source document:\n"); Console.WriteLine($"{JsonSerializer.Serialize(sourceDoc, options)}\n"); Console.WriteLine("The target document:\n"); Console.WriteLine($"{JsonSerializer.Serialize(targetDoc, options)}\n"); Console.WriteLine("Patch to be applied to source:\n"); Console.WriteLine($"{JsonSerializer.Serialize(patch, options)}\n"); using JsonDocument result = JsonMergePatch.ApplyMergePatch(sourceDoc.RootElement, patch.RootElement); Debug.Assert(JsonElementEqualityComparer.Instance.Equals(result.RootElement, targetDoc.RootElement)); }
public void RunJsonMergePatchTests(string path) { var serializerOptions = new JsonSerializerOptions() { WriteIndented = true }; Debug.WriteLine($"Test {path}"); string text = System.IO.File.ReadAllText(path); var jsonOptions = new JsonDocumentOptions(); jsonOptions.CommentHandling = JsonCommentHandling.Skip; using JsonDocument doc = JsonDocument.Parse(text, jsonOptions); var testsEnumeratable = doc.RootElement.EnumerateArray(); var comparer = JsonElementEqualityComparer.Instance; foreach (var testGroup in testsEnumeratable) { JsonElement given = testGroup.GetProperty("given"); var testCases = testGroup.GetProperty("cases"); var testCasesEnumeratable = testCases.EnumerateArray(); foreach (var testCase in testCasesEnumeratable) { string comment; JsonElement commentElement; if (testCase.TryGetProperty("comment", out commentElement) && commentElement.ValueKind == JsonValueKind.String) { comment = commentElement.GetString(); } else { comment = ""; } try { JsonElement patch; Assert.IsTrue(testCase.TryGetProperty("patch", out patch)); JsonElement expected; if (testCase.TryGetProperty("result", out expected)) { using JsonDocument result = JsonMergePatch.ApplyMergePatch(given, patch); Assert.IsTrue(comparer.Equals(result.RootElement, expected)); using JsonDocument patch2 = JsonMergePatch.FromDiff(given, result.RootElement); using JsonDocument result2 = JsonMergePatch.ApplyMergePatch(given, patch2.RootElement); Assert.IsTrue(comparer.Equals(result2.RootElement, expected)); } } catch (Exception e) { Debug.WriteLine("File: {0}", path); Debug.WriteLine("Error: {0}", e.Message); if (comment.Length > 0) { Debug.WriteLine($"Comment: {comment}"); } Console.WriteLine($"{JsonSerializer.Serialize(given, serializerOptions)}\n"); throw e; } } } }