private async Task TestDeserialization <TElement>( Stream memoryStream, string expectedJson, Type type, JsonSerializerOptions options) { try { object deserialized = await Serializer.DeserializeWrapper(memoryStream, type, options); string serialized = JsonSerializer.Serialize(deserialized, options); // Stack elements reversed during serialization. if (StackTypes <TElement>().Contains(type)) { deserialized = JsonSerializer.Deserialize(serialized, type, options); serialized = JsonSerializer.Serialize(deserialized, options); } // TODO: https://github.com/dotnet/runtime/issues/35611. // Can't control order of dictionary elements when serializing, so reference metadata might not match up. if (!(CollectionTestTypes.DictionaryTypes <TElement>().Contains(type) && options.ReferenceHandler == ReferenceHandler.Preserve)) { JsonTestHelper.AssertJsonEqual(expectedJson, serialized); } } catch (NotSupportedException ex) { Assert.True(GetTypesNotSupportedForDeserialization <TElement>().Contains(type)); Assert.Contains(type.ToString(), ex.ToString()); } }
private static async Task TestDeserialization <TElement>( Stream memoryStream, string expectedJson, Type type, JsonSerializerOptions options) { try { object deserialized = await JsonSerializer.DeserializeAsync(memoryStream, type, options); string serialized = JsonSerializer.Serialize(deserialized, options); // Stack elements reversed during serialization. if (StackTypes <TElement>().Contains(type)) { deserialized = JsonSerializer.Deserialize(serialized, type, options); serialized = JsonSerializer.Serialize(deserialized, options); } // Can't control order of dictionary elements when serializing, so reference metadata might not match up. if (!(DictionaryTypes <TElement>().Contains(type) && options.ReferenceHandling == ReferenceHandling.Preserve)) { JsonTestHelper.AssertJsonEqual(expectedJson, serialized); } } catch (NotSupportedException ex) { Assert.True(GetTypesNotSupportedForDeserialization <TElement>().Contains(type)); Assert.Contains(type.ToString(), ex.ToString()); } }
public static void NullableValueTypedMemberWithNullsToObjectConverter() { const string expected = @"{""MyValueTypedProperty"":null,""MyRefTypedProperty"":null,""MyValueTypedField"":null,""MyRefTypedField"":null}"; var converter = new ValueTypeToObjectConverter(); var options = new JsonSerializerOptions() { IncludeFields = true, }; options.Converters.Add(converter); string json; { var obj = new TestClassWithNullableValueTypedMember(); json = JsonSerializer.Serialize(obj, options); Assert.Equal(4, converter.WriteCallCount); JsonTestHelper.AssertJsonEqual(expected, json); } { var obj = JsonSerializer.Deserialize <TestClassWithNullableValueTypedMember>(json, options); Assert.Equal(4, converter.ReadCallCount); Assert.Null(obj.MyValueTypedProperty); Assert.Null(obj.MyValueTypedField); Assert.Null(obj.MyRefTypedProperty); Assert.Null(obj.MyRefTypedField); } }
private async Task TestDeserialization <TCollection, TElement>(string json, JsonSerializerOptions options) { if (TypeHelper <TElement> .NotSupportedForDeserialization.Contains(typeof(TCollection))) { NotSupportedException exception = await Assert.ThrowsAsync <NotSupportedException>(() => Serializer.DeserializeWrapper <TCollection>(json, options)); Assert.Contains(typeof(TCollection).ToString(), exception.ToString()); return; } TCollection deserialized = await Serializer.DeserializeWrapper <TCollection>(json, options); // Validate the integrity of the deserialized value by reserializing // it using the non-streaming serializer and comparing the roundtripped value. string roundtrippedJson = JsonSerializer.Serialize(deserialized, options); // Stack elements reversed during serialization. if (TypeHelper <TElement> .StackTypes.Contains(typeof(TCollection))) { deserialized = JsonSerializer.Deserialize <TCollection>(roundtrippedJson, options); roundtrippedJson = JsonSerializer.Serialize(deserialized, options); } // TODO: https://github.com/dotnet/runtime/issues/35611. // Can't control order of dictionary elements when serializing, so reference metadata might not match up. if (options.ReferenceHandler == ReferenceHandler.Preserve && TypeHelper <TElement> .DictionaryTypes.Contains(typeof(TCollection))) { return; } JsonTestHelper.AssertJsonEqual(json, roundtrippedJson); }
public async Task WriteNestedAsyncEnumerable_Nullable <TElement>(IEnumerable <TElement> source, int delayInterval, int bufferSize) { if (StreamingSerializer?.IsAsyncSerializer != true) { return; } // Primarily tests the ability of NullableConverter to flow async serialization state JsonSerializerOptions options = new JsonSerializerOptions { DefaultBufferSize = bufferSize, IncludeFields = true, }; string expectedJson = JsonSerializer.Serialize <(IEnumerable <TElement>, bool)?>((source, false), options); using var stream = new Utf8MemoryStream(); var asyncEnumerable = new MockedAsyncEnumerable <TElement>(source, delayInterval); await StreamingSerializer.SerializeWrapper <(IAsyncEnumerable <TElement>, bool)?>(stream, (asyncEnumerable, false), options); JsonTestHelper.AssertJsonEqual(expectedJson, stream.AsString()); Assert.Equal(1, asyncEnumerable.TotalCreatedEnumerators); Assert.Equal(1, asyncEnumerable.TotalDisposedEnumerators); }
public async Task WriteAsyncEnumerableOfAsyncEnumerables <TElement>(IEnumerable <TElement> source, int delayInterval, int bufferSize) { if (StreamingSerializer?.IsAsyncSerializer != true) { return; } JsonSerializerOptions options = new JsonSerializerOptions { DefaultBufferSize = bufferSize }; const int OuterEnumerableCount = 5; string expectedJson = JsonSerializer.Serialize(Enumerable.Repeat(source, OuterEnumerableCount)); var innerAsyncEnumerable = new MockedAsyncEnumerable <TElement>(source, delayInterval); var outerAsyncEnumerable = new MockedAsyncEnumerable <IAsyncEnumerable <TElement> >( Enumerable.Repeat(innerAsyncEnumerable, OuterEnumerableCount), delayInterval); using var stream = new Utf8MemoryStream(); await StreamingSerializer.SerializeWrapper(stream, outerAsyncEnumerable, options); JsonTestHelper.AssertJsonEqual(expectedJson, stream.AsString()); Assert.Equal(1, outerAsyncEnumerable.TotalCreatedEnumerators); Assert.Equal(1, outerAsyncEnumerable.TotalDisposedEnumerators); Assert.Equal(OuterEnumerableCount, innerAsyncEnumerable.TotalCreatedEnumerators); Assert.Equal(OuterEnumerableCount, innerAsyncEnumerable.TotalDisposedEnumerators); }
public static void ValueTypedMemberToInterfaceConverter() { const string expected = @"{""MyValueTypedProperty"":""ValueTypedProperty"",""MyRefTypedProperty"":""RefTypedProperty"",""MyValueTypedField"":""ValueTypedField"",""MyRefTypedField"":""RefTypedField""}"; var converter = new ValueTypeToInterfaceConverter(); var options = new JsonSerializerOptions() { IncludeFields = true, }; options.Converters.Add(converter); string json; { var obj = new TestClassWithValueTypedMember(); obj.Initialize(); obj.Verify(); json = JsonSerializer.Serialize(obj, options); Assert.Equal(4, converter.WriteCallCount); JsonTestHelper.AssertJsonEqual(expected, json); } { var obj = JsonSerializer.Deserialize <TestClassWithValueTypedMember>(json, options); obj.Verify(); Assert.Equal(4, converter.ReadCallCount); } }
public static void CreateDom_ImplicitOperators() { var jObj = new JsonObject { // Primitives ["MyString"] = "Hello!", ["MyNull"] = null, ["MyBoolean"] = false, // Nested array ["MyArray"] = new JsonArray(2, 3, 42), // Additional primitives ["MyInt"] = 43, ["MyDateTime"] = new DateTime(2020, 7, 8), ["MyGuid"] = new Guid("ed957609-cdfe-412f-88c1-02daca1b4f51"), // Nested objects ["MyObject"] = new JsonObject { ["MyString"] = "Hello!!" }, ["Child"] = new JsonObject() { ["ChildProp"] = 1 } }; string json = jObj.ToJsonString(); JsonTestHelper.AssertJsonEqual(JsonNodeTests.ExpectedDomJson, json); }
public static void ExpandoObject() { ExpandoObject expando = JsonSerializer.Deserialize <ExpandoObject>(Json); Assert.Equal(8, ((IDictionary <string, object>)expando).Keys.Count); dynamic obj = expando; VerifyPrimitives(); VerifyObject(); VerifyArray(); // Re-serialize string json = JsonSerializer.Serialize <ExpandoObject>(obj); JsonTestHelper.AssertJsonEqual(Json, json); json = JsonSerializer.Serialize <dynamic>(obj); JsonTestHelper.AssertJsonEqual(Json, json); json = JsonSerializer.Serialize(obj); JsonTestHelper.AssertJsonEqual(Json, json); void VerifyPrimitives() { JsonElement jsonElement = obj.MyString; Assert.Equal("Hello", jsonElement.GetString()); jsonElement = obj.MyBoolean; Assert.True(jsonElement.GetBoolean()); jsonElement = obj.MyInt; Assert.Equal(42, jsonElement.GetInt32()); jsonElement = obj.MyDateTime; Assert.Equal(MyDateTime, jsonElement.GetDateTime()); jsonElement = obj.MyGuid; Assert.Equal(MyGuid, jsonElement.GetGuid()); } void VerifyObject() { JsonElement jsonElement = obj.MyObject; // Here we access a property on a nested object and must use JsonElement (not a dynamic property). Assert.Equal("World", jsonElement.GetProperty("MyString").GetString()); } void VerifyArray() { JsonElement jsonElement = obj.MyArray; Assert.Equal(2, jsonElement.EnumerateArray().Count()); } }
protected static void AssertFastPathLogicCorrect <T>(string expectedJson, T value, JsonTypeInfo <T> typeInfo) { using MemoryStream ms = new(); using Utf8JsonWriter writer = new(ms); typeInfo.Serialize !(writer, value); writer.Flush(); JsonTestHelper.AssertJsonEqual(expectedJson, Encoding.UTF8.GetString(ms.ToArray())); }
public static void JsonDynamicTypes_Serialize() { var options = new JsonSerializerOptions(); options.EnableDynamicTypes(); // Guid (string) string GuidJson = $"{DynamicTests.MyGuid.ToString("D")}"; string GuidJsonWithQuotes = $"\"{GuidJson}\""; dynamic dynamicString = new JsonDynamicString(GuidJson, options); Assert.Equal(DynamicTests.MyGuid, (Guid)dynamicString); string json = JsonSerializer.Serialize(dynamicString, options); Assert.Equal(GuidJsonWithQuotes, json); // char (string) dynamicString = new JsonDynamicString("a", options); Assert.Equal('a', (char)dynamicString); json = JsonSerializer.Serialize(dynamicString, options); Assert.Equal("\"a\"", json); // Number (JsonElement) using (JsonDocument doc = JsonDocument.Parse($"{decimal.MaxValue}")) { dynamic dynamicNumber = new JsonDynamicNumber(doc.RootElement, options); Assert.Equal <decimal>(decimal.MaxValue, (decimal)dynamicNumber); json = JsonSerializer.Serialize(dynamicNumber, options); Assert.Equal(decimal.MaxValue.ToString(), json); } // Boolean dynamic dynamicBool = new JsonDynamicBoolean(true, options); Assert.True(dynamicBool); json = JsonSerializer.Serialize(dynamicBool, options); Assert.Equal("true", json); // Array dynamic arr = new JsonDynamicArray(options); arr.Add(1); arr.Add(2); json = JsonSerializer.Serialize(arr, options); Assert.Equal("[1,2]", json); // Object dynamic dynamicObject = new JsonDynamicObject(options); dynamicObject["One"] = 1; dynamicObject["Two"] = 2; json = JsonSerializer.Serialize(dynamicObject, options); JsonTestHelper.AssertJsonEqual("{\"One\":1,\"Two\":2}", json); }
public static void NamingPoliciesAreNotUsed() { const string Json = "{\"myProperty\":42}"; var options = new JsonSerializerOptions(); options.PropertyNamingPolicy = new SimpleSnakeCasePolicy(); JsonObject obj = JsonSerializer.Deserialize<JsonObject>(Json, options); string json = obj.ToJsonString(); JsonTestHelper.AssertJsonEqual(Json, json); }
public static void SupportedTypeRoundtrip <T>(JsonTypeInfo <T> jsonTypeInfo, T value, string expectedJson) { string json = JsonSerializer.Serialize(value, jsonTypeInfo); JsonTestHelper.AssertJsonEqual(expectedJson, json); T deserializedValue = JsonSerializer.Deserialize(json, jsonTypeInfo); json = JsonSerializer.Serialize(deserializedValue, jsonTypeInfo); JsonTestHelper.AssertJsonEqual(expectedJson, json); }
public void RoundtripJsonElement(string json) { JsonElement jsonElement = JsonDocument.Parse(json).RootElement; string actualJson = JsonSerializer.Serialize(jsonElement, DefaultContext.JsonElement); JsonTestHelper.AssertJsonEqual(json, actualJson); JsonElement actualJsonElement = JsonSerializer.Deserialize(actualJson, DefaultContext.JsonElement); JsonTestHelper.AssertJsonEqual(jsonElement, actualJsonElement); }
public static void CreateDom_UnknownTypeHandling() { var options = new JsonSerializerOptions(); options.UnknownTypeHandling = JsonUnknownTypeHandling.JsonNode; string GuidJson = $"{Serialization.Tests.DynamicTests.MyGuid.ToString("D")}"; // We can't convert an unquoted string to a Guid dynamic dynamicString = JsonValue.Create(GuidJson); InvalidOperationException ex = Assert.Throws <InvalidOperationException>(() => (Guid)dynamicString); // "A value of type 'System.String' cannot be converted to a 'System.Guid'." Assert.Contains(typeof(string).ToString(), ex.Message); Assert.Contains(typeof(Guid).ToString(), ex.Message); string json; // Number (JsonElement) using (JsonDocument doc = JsonDocument.Parse($"{decimal.MaxValue}")) { dynamic dynamicNumber = JsonValue.Create(doc.RootElement); Assert.Equal(decimal.MaxValue, (decimal)dynamicNumber); json = dynamicNumber.ToJsonString(options); Assert.Equal(decimal.MaxValue.ToString(), json); } // Boolean dynamic dynamicBool = JsonValue.Create(true); Assert.True((bool)dynamicBool); json = dynamicBool.ToJsonString(options); Assert.Equal("true", json); // Array dynamic arr = new JsonArray(); arr.Add(1); arr.Add(2); json = arr.ToJsonString(options); Assert.Equal("[1,2]", json); // Object dynamic dynamicObject = new JsonObject(); dynamicObject.One = 1; dynamicObject.Two = 2; json = dynamicObject.ToJsonString(options); JsonTestHelper.AssertJsonEqual("{\"One\":1,\"Two\":2}", json); }
public static void ClassWithPrimitivesObjectConverter() { string expected = @"{ ""MyIntProperty"":123, ""MyBoolProperty"":true, ""MyStringProperty"":""Hello"", ""MyIntField"":321, ""MyBoolField"":true, ""MyStringField"":""World"" }"; string json; var converter = new PrimitiveConverter(); var options = new JsonSerializerOptions { IncludeFields = true }; options.Converters.Add(converter); { var obj = new ClassWithPrimitives { MyIntProperty = 123, MyBoolProperty = true, MyStringProperty = "Hello", MyIntField = 321, MyBoolField = true, MyStringField = "World", }; json = JsonSerializer.Serialize(obj, options); Assert.Equal(6, converter.WriteCallCount); JsonTestHelper.AssertJsonEqual(expected, json); } { var obj = JsonSerializer.Deserialize <ClassWithPrimitives>(json, options); Assert.Equal(6, converter.ReadCallCount); Assert.Equal(123, obj.MyIntProperty); Assert.True(obj.MyBoolProperty); Assert.Equal("Hello", obj.MyStringProperty); Assert.Equal(321, obj.MyIntField); Assert.True(obj.MyBoolField); Assert.Equal("World", obj.MyStringField); } }
public override void NullableStruct() { PersonStruct?person = new() { FirstName = "Jane", LastName = "Doe" }; string json = JsonSerializer.Serialize(person, DefaultContext.NullablePersonStruct); JsonTestHelper.AssertJsonEqual(@"{""FirstName"":""Jane"",""LastName"":""Doe""}", json); Assert.Throws <InvalidOperationException>(() => JsonSerializer.Deserialize(json, DefaultContext.NullablePersonStruct)); } }
public static void ComplexReferenceTypeConverter_NullOptIn() { // Per null handling opt-in, converter handles null. var options = new JsonSerializerOptions(); options.Converters.Add(new PointClassConverter_NullOptIn()); Point_2D obj = JsonSerializer.Deserialize <Point_2D>("null", options); Assert.Equal(-1, obj.X); Assert.Equal(-1, obj.Y); obj = null; JsonTestHelper.AssertJsonEqual(@"{""X"":-1,""Y"":-1}", JsonSerializer.Serialize(obj, options)); }
public static void NamingPoliciesAreNotUsed() { const string Json = "{\"myProperty\":42}"; var options = new JsonSerializerOptions(); options.EnableDynamicTypes(); options.PropertyNamingPolicy = new SimpleSnakeCasePolicy(); dynamic obj = JsonSerializer.Deserialize <dynamic>(Json, options); string json = JsonSerializer.Serialize(obj, options); JsonTestHelper.AssertJsonEqual(Json, json); }
public static void FastPathInvokedForNullableUnderlyingType() { PersonStruct?person = new() { FirstName = "Jane", LastName = "Doe" }; NullablePersonContext context = new(); Assert.False(context.FastPathCalled); string json = JsonSerializer.Serialize(person, context.NullablePersonStruct); Assert.True(context.FastPathCalled); JsonTestHelper.AssertJsonEqual(@"{""FirstName"":""Jane"",""LastName"":""Doe""}", json); }
public async Task WriteNestedAsyncEnumerable <TElement>(IEnumerable <TElement> source, int delayInterval, int bufferSize) { JsonSerializerOptions options = new JsonSerializerOptions { DefaultBufferSize = bufferSize }; string expectedJson = await JsonSerializerWrapperForString.SerializeWrapper(new { Data = source }); using var stream = new Utf8MemoryStream(); var asyncEnumerable = new MockedAsyncEnumerable <TElement>(source, delayInterval); await JsonSerializerWrapperForStream.SerializeWrapper(stream, new { Data = asyncEnumerable }, options); JsonTestHelper.AssertJsonEqual(expectedJson, stream.ToString()); Assert.Equal(1, asyncEnumerable.TotalCreatedEnumerators); Assert.Equal(1, asyncEnumerable.TotalDisposedEnumerators); }
public static async Task WriteRootLevelAsyncEnumerable <TElement>(IEnumerable <TElement> source, int delayInterval, int bufferSize) { JsonSerializerOptions options = new JsonSerializerOptions { DefaultBufferSize = bufferSize }; string expectedJson = JsonSerializer.Serialize(source); using var stream = new Utf8MemoryStream(); var asyncEnumerable = new MockedAsyncEnumerable <TElement>(source, delayInterval); await JsonSerializer.SerializeAsync(stream, asyncEnumerable, options); JsonTestHelper.AssertJsonEqual(expectedJson, stream.ToString()); Assert.Equal(1, asyncEnumerable.TotalCreatedEnumerators); Assert.Equal(1, asyncEnumerable.TotalDisposedEnumerators); }
public static void VerifyMutableDom_WithoutUsingDynamicKeyword_JsonDynamicType() { var options = new JsonSerializerOptions(); options.EnableDynamicTypes(); JsonDynamicObject obj = (JsonDynamicObject)JsonSerializer.Deserialize <object>(DynamicTests.Json, options); Verify(); // Verify the values are round-trippable. ((JsonDynamicArray)obj["MyArray"]).RemoveAt(2); Verify(); void Verify() { // Change some primitives. ((JsonDynamicType)obj["MyString"]).SetValue("Hello!"); ((JsonDynamicType)obj["MyBoolean"]).SetValue(false); ((JsonDynamicType)obj["MyInt"]).SetValue(43); // Add nested objects. obj["MyObject"] = new JsonDynamicObject(options) { ["MyString"] = new JsonDynamicString("Hello!!", options) }; obj["Child"] = new JsonDynamicObject(options) { ["ChildProp"] = new JsonDynamicNumber(1, options) }; // Modify number elements. var arr = (JsonDynamicArray)obj["MyArray"]; ((JsonDynamicType)arr[0]).SetValue(2); ((JsonDynamicType)arr[1]).SetValue(3); // Add an element. arr.Add(new JsonDynamicNumber(42, options)); string json = JsonSerializer.Serialize(obj, options); JsonTestHelper.AssertJsonEqual(ExpectedDomJson, json); } }
public static void VerifyMutableDom_UsingDynamicKeyword() { var options = new JsonSerializerOptions(); options.EnableDynamicTypes(); dynamic obj = JsonSerializer.Deserialize <dynamic>(DynamicTests.Json, options); Assert.IsType <JsonDynamicObject>(obj); // Change some primitives. obj.MyString = "Hello!"; obj.MyBoolean = false; obj.MyInt = 43; // Add nested objects. // Use JsonDynamicObject; ExpandoObject should not be used since it doesn't have the same semantics including // null handling and case-sensitivity that respects JsonSerializerOptions.PropertyNameCaseInsensitive. dynamic myObject = new JsonDynamicObject(options); myObject.MyString = "Hello!!"; obj.MyObject = myObject; dynamic child = new JsonDynamicObject(options); child.ChildProp = 1; obj.Child = child; // Modify number elements. dynamic arr = obj["MyArray"]; arr[0] = (int)arr[0] + 1; arr[1] = (int)arr[1] + 1; // Add an element. arr.Add(42); string json = JsonSerializer.Serialize(obj, options); JsonTestHelper.AssertJsonEqual(ExpectedDomJson, json); }
public static void UnknownTypeHandling_Object() { var options = new JsonSerializerOptions(); options.UnknownTypeHandling = JsonUnknownTypeHandling.JsonNode; dynamic obj = JsonSerializer.Deserialize <object>(Serialization.Tests.DynamicTests.Json, options); Assert.IsAssignableFrom <JsonObject>(obj); // Change some primitives. obj.MyString = "Hello!"; obj.MyBoolean = false; obj.MyInt = 43; // Add nested objects. // Use JsonObject; ExpandoObject should not be used since it doesn't have the same semantics including // null handling and case-sensitivity that respects JsonSerializerOptions.PropertyNameCaseInsensitive. dynamic myObject = new JsonObject(); myObject.MyString = "Hello!!"; obj.MyObject = myObject; dynamic child = new JsonObject(); child.ChildProp = 1; obj.Child = child; // Modify number elements. dynamic arr = obj.MyArray; arr[0] = (int)arr[0] + 1; arr[1] = (int)arr[1] + 1; // Add an element. arr.Add(42); string json = obj.ToJsonString(options); JsonTestHelper.AssertJsonEqual(JsonNodeTests.ExpectedDomJson, json); }
public static void VerifyMutableDom_WithoutUsingDynamicKeyword() { var options = new JsonSerializerOptions(); options.EnableDynamicTypes(); JsonDynamicObject obj = (JsonDynamicObject)JsonSerializer.Deserialize <object>(DynamicTests.Json, options); // Change some primitives. obj["MyString"] = "Hello!"; obj["MyBoolean"] = false; obj["MyInt"] = 43; // Add nested objects. obj["MyObject"] = new JsonDynamicObject(options) { ["MyString"] = "Hello!!" }; obj["Child"] = new JsonDynamicObject(options) { ["ChildProp"] = 1 }; // Modify number elements. var arr = (JsonDynamicArray)obj["MyArray"]; var elem = (JsonDynamicNumber)arr[0]; elem.SetValue(elem.GetValue <int>() + 1); elem = (JsonDynamicNumber)arr[1]; elem.SetValue(elem.GetValue <int>() + 1); // Add an element. arr.Add(42); string json = JsonSerializer.Serialize(obj, options); JsonTestHelper.AssertJsonEqual(ExpectedDomJson, json); }
public static void EditDom() { const string Json = "{\"MyString\":\"Hello\",\"MyNull\":null,\"MyBoolean\":true,\"MyArray\":[1,2],\"MyInt\":42,\"MyDateTime\":\"2020-07-08T00:00:00\",\"MyGuid\":\"ed957609-cdfe-412f-88c1-02daca1b4f51\",\"MyObject\":{\"MyString\":\"World\"}}"; JsonNode obj = JsonSerializer.Deserialize <JsonObject>(Json); Verify(); // Verify the values are round-trippable. ((JsonArray)obj["MyArray"]).RemoveAt(2); Verify(); void Verify() { // Change some primitives. obj["MyString"] = JsonValue.Create("Hello!"); obj["MyBoolean"] = JsonValue.Create(false); obj["MyInt"] = JsonValue.Create(43); // Add nested objects. obj["MyObject"] = new JsonObject(); obj["MyObject"]["MyString"] = JsonValue.Create("Hello!!"); obj["Child"] = new JsonObject(); obj["Child"]["ChildProp"] = JsonValue.Create(1); // Modify number elements. obj["MyArray"][0] = JsonValue.Create(2); obj["MyArray"][1] = JsonValue.Create(3); // Add an element. ((JsonArray)obj["MyArray"]).Add(JsonValue.Create(42)); string json = obj.ToJsonString(); JsonTestHelper.AssertJsonEqual(JsonNodeTests.ExpectedDomJson, json); } }
private async Task PerformSerialization <TCollection, TElement>( TCollection collection, JsonSerializerOptions options) { string expectedjson = JsonSerializer.Serialize(collection, options); string actualJson = await Serializer.SerializeWrapper(collection, options); JsonTestHelper.AssertJsonEqual(expectedjson, actualJson); if (options.ReferenceHandler == ReferenceHandler.Preserve && TypeHelper <TElement> .NonRoundtrippableWithReferenceHandler.Contains(typeof(TCollection))) { return; } await TestDeserialization <TCollection, TElement>(actualJson, options); // Deserialize with extra whitespace string jsonWithWhiteSpace = GetPayloadWithWhiteSpace(actualJson); await TestDeserialization <TCollection, TElement>(jsonWithWhiteSpace, options); }
public async Task WriteSequentialNestedAsyncEnumerables <TElement>(IEnumerable <TElement> source, int delayInterval, int bufferSize) { if (StreamingSerializer?.IsAsyncSerializer != true) { return; } JsonSerializerOptions options = new JsonSerializerOptions { DefaultBufferSize = bufferSize }; string expectedJson = JsonSerializer.Serialize(new { Data1 = source, Data2 = source }); using var stream = new Utf8MemoryStream(); var asyncEnumerable = new MockedAsyncEnumerable <TElement>(source, delayInterval); await StreamingSerializer.SerializeWrapper(stream, new { Data1 = asyncEnumerable, Data2 = asyncEnumerable }, options); JsonTestHelper.AssertJsonEqual(expectedJson, stream.AsString()); Assert.Equal(2, asyncEnumerable.TotalCreatedEnumerators); Assert.Equal(2, asyncEnumerable.TotalDisposedEnumerators); }
public static void CreateDom() { var jObj = new JsonObject { // Primitives ["MyString"] = JsonValue.Create("Hello!"), ["MyNull"] = null, ["MyBoolean"] = JsonValue.Create(false), // Nested array ["MyArray"] = new JsonArray ( JsonValue.Create(2), JsonValue.Create(3), JsonValue.Create(42) ), // Additional primitives ["MyInt"] = JsonValue.Create(43), ["MyDateTime"] = JsonValue.Create(new DateTime(2020, 7, 8)), ["MyGuid"] = JsonValue.Create(new Guid("ed957609-cdfe-412f-88c1-02daca1b4f51")), // Nested objects ["MyObject"] = new JsonObject { ["MyString"] = JsonValue.Create("Hello!!") }, ["Child"] = new JsonObject { ["ChildProp"] = JsonValue.Create(1) } }; string json = jObj.ToJsonString(); JsonTestHelper.AssertJsonEqual(JsonNodeTests.ExpectedDomJson, json); }