public async Task WriteArrayOfHashSetT() { HashSet <int>[] input = new HashSet <int> [2]; input[0] = new HashSet <int>(new List <int> { 1, 2 }); input[1] = new HashSet <int>(new List <int> { 3, 4 }); string json = await JsonSerializerWrapperForString.SerializeWrapper(input); // Because order isn't guaranteed, roundtrip data to ensure write was accurate. input = await JsonSerializerWrapperForString.DeserializeWrapper <HashSet <int>[]>(json); Assert.Equal(new HashSet <int> { 1, 2 }, input.First()); Assert.Equal(new HashSet <int> { 3, 4 }, input.Last()); }
public async Task ReadPrimitiveIEnumerable() { IEnumerable result = await JsonSerializerWrapperForString.DeserializeWrapper <IEnumerable>(@"[1,2]"); int expected = 1; foreach (JsonElement i in result) { Assert.Equal(expected++, i.GetInt32()); } result = await JsonSerializerWrapperForString.DeserializeWrapper <IEnumerable>(@"[]"); int count = 0; IEnumerator e = result.GetEnumerator(); while (e.MoveNext()) { count++; } Assert.Equal(0, count); }
public async Task Read_SpecializedCollection() { BitVector32 bv32 = await JsonSerializerWrapperForString.DeserializeWrapper <BitVector32>(@"{""Data"":4}"); // Data property is skipped because it doesn't have a setter. Assert.Equal(0, bv32.Data); HybridDictionary hd = await JsonSerializerWrapperForString.DeserializeWrapper <HybridDictionary>(@"{""key"":""value""}"); Assert.Equal(1, hd.Count); Assert.Equal("value", ((JsonElement)hd["key"]).GetString()); IOrderedDictionary iod = await JsonSerializerWrapperForString.DeserializeWrapper <OrderedDictionary>(@"{""key"":""value""}"); Assert.Equal(1, iod.Count); Assert.Equal("value", ((JsonElement)iod["key"]).GetString()); ListDictionary ld = await JsonSerializerWrapperForString.DeserializeWrapper <ListDictionary>(@"{""key"":""value""}"); Assert.Equal(1, ld.Count); Assert.Equal("value", ((JsonElement)ld["key"]).GetString()); }
public async Task WriteHashSetTOfISetT() { HashSet <ISet <int> > input = new HashSet <ISet <int> > { new HashSet <int>() { 1, 2 }, new HashSet <int>() { 3, 4 } }; string json = await JsonSerializerWrapperForString.SerializeWrapper(input); // Because order isn't guaranteed, roundtrip data to ensure write was accurate. input = await JsonSerializerWrapperForString.DeserializeWrapper <HashSet <ISet <int> > >(json); if (input.First().Contains(1)) { Assert.Equal(new HashSet <int> { 1, 2 }, input.First()); Assert.Equal(new HashSet <int> { 3, 4 }, input.Last()); } else { Assert.Equal(new HashSet <int> { 3, 4 }, input.First()); Assert.Equal(new HashSet <int> { 1, 2 }, input.Last()); } }
public async Task RandomReferenceMetadataNotSupported() { string json = @"{""Name"":""Jet"",""$random"":10}"; // Baseline, preserve ref feature off. var employee = await JsonSerializerWrapperForString.DeserializeWrapper <Employee>(json); Assert.Equal("Jet", employee.Name); // Metadata not supported with preserve ref feature on. var options = new JsonSerializerOptions { ReferenceHandler = ReferenceHandler.Preserve }; NotSupportedException ex = await Assert.ThrowsAsync <NotSupportedException>(() => JsonSerializerWrapperForString.DeserializeWrapper <Employee>(json, options)); string exStr = ex.ToString(); Assert.Contains("System.Text.Json.Serialization.Tests.ConstructorTests+Employee", exStr); Assert.Contains("$.$random", exStr); }
public virtual async Task Honor_JsonSerializablePropertyAttribute_OnProperties() { string json = @"{ ""MyInt"":1, ""MyString"":""Hello"", ""MyFloat"":2, ""MyUri"":""https://microsoft.com"" }"; var obj = await JsonSerializerWrapperForString.DeserializeWrapper <MyClass_WithNonPublicAccessors_WithPropertyAttributes>(json); Assert.Equal(1, obj.MyInt); Assert.Equal("Hello", obj.MyString); Assert.Equal(2f, obj.GetMyFloat); Assert.Equal(new Uri("https://microsoft.com"), obj.MyUri); json = await JsonSerializerWrapperForString.SerializeWrapper(obj); Assert.Contains(@"""MyInt"":1", json); Assert.Contains(@"""MyString"":""Hello""", json); Assert.Contains(@"""MyFloat"":2", json); Assert.Contains(@"""MyUri"":""https://microsoft.com""", json); }
public async Task NonPublic_AccessorsNotSupported_WithoutAttribute() { string json = @"{ ""MyInt"":1, ""MyString"":""Hello"", ""MyFloat"":2, ""MyUri"":""https://microsoft.com"" }"; var obj = await JsonSerializerWrapperForString.DeserializeWrapper <MyClass_WithNonPublicAccessors>(json); Assert.Equal(0, obj.MyInt); Assert.Null(obj.MyString); Assert.Equal(2f, obj.GetMyFloat); Assert.Equal(new Uri("https://microsoft.com"), obj.MyUri); json = await JsonSerializerWrapperForString.SerializeWrapper(obj); Assert.Contains(@"""MyInt"":0", json); Assert.Contains(@"""MyString"":null", json); Assert.DoesNotContain(@"""MyFloat"":", json); Assert.DoesNotContain(@"""MyUri"":", json); }
public async Task HonorCustomEncoder() { var kvp = new KeyValuePair <int, int>(1, 2); JsonNamingPolicy namingPolicy = new TrailingAngleBracketPolicy(); // Baseline - properties serialized with default encoder if none specified. var options = new JsonSerializerOptions { PropertyNamingPolicy = namingPolicy, }; Assert.Equal(@"{""Key\u003C"":1,""Value\u003C"":2}", await JsonSerializerWrapperForString.SerializeWrapper(kvp, options)); // Test - serializer honors custom encoder. options = new JsonSerializerOptions { PropertyNamingPolicy = namingPolicy, Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping }; Assert.Equal(@"{""Key<"":1,""Value<"":2}", await JsonSerializerWrapperForString.SerializeWrapper(kvp, options)); }
public async Task ReadPrimitiveIImmutableSetT() { IImmutableSet <int> result = await JsonSerializerWrapperForString.DeserializeWrapper <IImmutableSet <int> >(@"[1,2]"); List <int> expected = new List <int> { 1, 2 }; foreach (int i in result) { expected.Remove(i); } Assert.Equal(0, expected.Count); result = await JsonSerializerWrapperForString.DeserializeWrapper <IImmutableSet <int> >(@"[]"); Assert.Equal(0, result.Count()); await Assert.ThrowsAsync <NotSupportedException>(async() => await JsonSerializerWrapperForString.DeserializeWrapper <StringIImmutableSetWrapper>(@"[""1"",""2""]")); await Assert.ThrowsAsync <NotSupportedException>(async() => await JsonSerializerWrapperForString.DeserializeWrapper <StringIImmutableSetWrapper>(@"[]")); }
public async Task UnicodePropertyNames() { ClassWithUnicodeProperty obj = await JsonSerializerWrapperForString.DeserializeWrapper <ClassWithUnicodeProperty>("{\"A\u0467\":1}"); Assert.Equal(1, obj.A\u0467); // Specifying encoder on options does not impact deserialize. var options = new JsonSerializerOptions(); options.Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping; obj = await JsonSerializerWrapperForString.DeserializeWrapper <ClassWithUnicodeProperty>("{\"A\u0467\":1}", options); Assert.Equal(1, obj.A\u0467); string json; // Verify the name is escaped after serialize. json = await JsonSerializerWrapperForString.SerializeWrapper(obj); Assert.Contains(@"""A\u0467"":1", json); // With custom escaper json = await JsonSerializerWrapperForString.SerializeWrapper(obj, options); Assert.Contains("\"A\u0467\":1", json); // Verify the name is unescaped after deserialize. obj = await JsonSerializerWrapperForString.DeserializeWrapper <ClassWithUnicodeProperty>(json); Assert.Equal(1, obj.A\u0467); // With custom escaper obj = await JsonSerializerWrapperForString.DeserializeWrapper <ClassWithUnicodeProperty>(json, options); Assert.Equal(1, obj.A\u0467); }
public async Task Write_ConcurrentCollection() { Assert.Equal(@"[""1""]", await JsonSerializerWrapperForString.SerializeWrapper(new BlockingCollection <string> { "1" })); Assert.Equal(@"[""1""]", await JsonSerializerWrapperForString.SerializeWrapper(new ConcurrentBag <string> { "1" })); Assert.Equal(@"{""key"":""value""}", await JsonSerializerWrapperForString.SerializeWrapper(new ConcurrentDictionary <string, string> { ["key"] = "value" })); ConcurrentQueue <string> qc = new ConcurrentQueue <string>(); qc.Enqueue("1"); Assert.Equal(@"[""1""]", await JsonSerializerWrapperForString.SerializeWrapper(qc)); ConcurrentStack <string> qs = new ConcurrentStack <string>(); qs.Push("1"); Assert.Equal(@"[""1""]", await JsonSerializerWrapperForString.SerializeWrapper(qs)); }
public async Task WriteAsyncEnumerableOfAsyncEnumerables <TElement>(IEnumerable <TElement> source, int delayInterval, int bufferSize) { JsonSerializerOptions options = new JsonSerializerOptions { DefaultBufferSize = bufferSize }; const int OuterEnumerableCount = 5; string expectedJson = await JsonSerializerWrapperForString.SerializeWrapper(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 JsonSerializerWrapperForStream.SerializeWrapper(stream, outerAsyncEnumerable, options); JsonTestHelper.AssertJsonEqual(expectedJson, stream.ToString()); Assert.Equal(1, outerAsyncEnumerable.TotalCreatedEnumerators); Assert.Equal(1, outerAsyncEnumerable.TotalDisposedEnumerators); Assert.Equal(OuterEnumerableCount, innerAsyncEnumerable.TotalCreatedEnumerators); Assert.Equal(OuterEnumerableCount, innerAsyncEnumerable.TotalDisposedEnumerators); }
public async Task ValueTypesShouldNotContainId() { //Struct as root. EmployeeStruct employee = new EmployeeStruct { Name = "Angela", //Struct as property. Job = new JobStruct { Title = "Software Engineer" }, //ImmutableArray<T> as property. Roles = ImmutableArray.Create( new RoleStruct { Description = "Contributor" }, new RoleStruct { Description = "Infrastructure" }) }; //ImmutableArray<T> as root. ImmutableArray <EmployeeStruct> array = //Struct as array element (same as struct being root). ImmutableArray.Create(employee); // Regardless of using preserve, do not emit $id to value types; that is why we compare against default. string actual = await JsonSerializerWrapperForString.SerializeWrapper(array, s_serializerOptionsPreserve); string expected = await JsonSerializerWrapperForString.SerializeWrapper(array); Assert.Equal(expected, actual); }
public async Task CustomNameSerialize_NullableValue() { var options = new JsonSerializerOptions { DictionaryKeyPolicy = new UppercaseNamingPolicy() // e.g. myint -> MYINT. }; Dictionary <string, int?> obj = new Dictionary <string, int?> { { "myint1", 1 }, { "myint2", 2 } }; const string Json = @"{""myint1"":1,""myint2"":2}"; const string JsonCustomKey = @"{""MYINT1"":1,""MYINT2"":2}"; // Without key policy option, serialize keys as they are. string json = await JsonSerializerWrapperForString.SerializeWrapper <object>(obj); Assert.Equal(Json, json); // With key policy option, serialize keys honoring the custom key policy. json = await JsonSerializerWrapperForString.SerializeWrapper <object>(obj, options); Assert.Equal(JsonCustomKey, json); }
public async Task UnicodePropertyNames() { ClassWithUnicodeProperty obj = new ClassWithUnicodeProperty { A\u0467 = 1 }; // Verify the name is escaped after serialize. string json = await JsonSerializerWrapperForString.SerializeWrapper(obj, s_serializerOptionsPreserve); Assert.StartsWith("{\"$id\":\"1\",", json); Assert.Contains(@"""A\u0467"":1", json); // Round-trip ClassWithUnicodeProperty objCopy = await JsonSerializerWrapperForString.DeserializeWrapper <ClassWithUnicodeProperty>(json, s_serializerOptionsPreserve); Assert.Equal(1, objCopy.A\u0467); // With custom escaper // Specifying encoder on options does not impact deserialize. var optionsWithEncoder = new JsonSerializerOptions { Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, ReferenceHandler = ReferenceHandler.Preserve }; json = await JsonSerializerWrapperForString.SerializeWrapper(obj, optionsWithEncoder); Assert.StartsWith("{\"$id\":\"1\",", json); Assert.Contains("\"A\u0467\":1", json); // Round-trip objCopy = await JsonSerializerWrapperForString.DeserializeWrapper <ClassWithUnicodeProperty>(json, optionsWithEncoder); Assert.Equal(1, objCopy.A\u0467); // We want to go over StackallocByteThreshold=256 to force a pooled allocation, so this property is 400 chars and 401 bytes. obj = new ClassWithUnicodeProperty { A\u046734567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890 = 1 }; // Verify the name is escaped after serialize. json = await JsonSerializerWrapperForString.SerializeWrapper(obj, s_serializerOptionsPreserve); Assert.StartsWith("{\"$id\":\"1\",", json); Assert.Contains(@"""A\u046734567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890"":1", json); // Round-trip objCopy = await JsonSerializerWrapperForString.DeserializeWrapper <ClassWithUnicodeProperty>(json, s_serializerOptionsPreserve); Assert.Equal(1, objCopy.A\u046734567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890); // With custom escaper json = await JsonSerializerWrapperForString.SerializeWrapper(obj, optionsWithEncoder); Assert.StartsWith("{\"$id\":\"1\",", json); Assert.Contains("\"A\u046734567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890\":1", json); // Round-trip objCopy = await JsonSerializerWrapperForString.DeserializeWrapper <ClassWithUnicodeProperty>(json, optionsWithEncoder); Assert.Equal(1, objCopy.A\u046734567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890); }
public ReferenceHandlerTests(JsonSerializerWrapperForString stringSerializer, JsonSerializerWrapperForStream streamSerializer) : base(stringSerializer, streamSerializer) { }
public async Task EscapingFails() { JsonException e = await Assert.ThrowsAsync <JsonException>(() => JsonSerializerWrapperForString.DeserializeWrapper <Parameterized_ClassWithUnicodeProperty>("{\"A\u0467\":bad}")); Assert.Equal("$.A\u0467", e.Path); }
public async Task PathForChildDictionaryFails(int bufferSize) { JsonSerializerOptions options = new() { DefaultBufferSize = bufferSize }; JsonException e = await Assert.ThrowsAsync <JsonException>(() => JsonSerializerWrapperForString.DeserializeWrapper <RootClass>(PathForChildDictionaryFails_Json, options)); Assert.Equal("$.Child.MyDictionary.Key", e.Path); }
public async Task PathForSpecialCharacterNestedFails() { JsonException e = await Assert.ThrowsAsync <JsonException>(() => JsonSerializerWrapperForString.DeserializeWrapper <RootClass>(@"{""Child"":{""Children"":[{}, {""MyDictionary"":{""K.e.y"": {""MyInt"":bad")); Assert.Equal("$.Child.Children[1].MyDictionary['K.e.y'].MyInt", e.Path); }
public async Task PathForChildPropertyFails() { JsonException e = await Assert.ThrowsAsync <JsonException>(() => JsonSerializerWrapperForString.DeserializeWrapper <RootClass>(@"{""Child"":{""MyInt"":bad]}")); Assert.Equal("$.Child.MyInt", e.Path); }
public async Task PathForChildListFails(int bufferSize) { JsonSerializerOptions options = new() { DefaultBufferSize = bufferSize }; JsonException e = await Assert.ThrowsAsync <JsonException>(() => JsonSerializerWrapperForString.DeserializeWrapper <RootClass>(PathForChildListFails_Json, options)); Assert.Contains("$.Child.MyIntArray", e.Path); }
public async Task CachingKeys() { ClassWithPropertyNamePermutations obj; void Verify() { Assert.Equal(1, obj.a); Assert.Equal(2, obj.aa); Assert.Equal(3, obj.aaa); Assert.Equal(4, obj.aaaa); Assert.Equal(5, obj.aaaaa); Assert.Equal(6, obj.aaaaaa); Assert.Equal(7, obj.aaaaaaa); Assert.Equal(7, obj.aaaaaab); Assert.Equal(8, obj.aaaaaaaa); Assert.Equal(8, obj.aaaaaaab); Assert.Equal(9, obj.aaaaaaaaa); Assert.Equal(9, obj.aaaaaaaab); Assert.Equal(2, obj.\u0467); Assert.Equal(4, obj.\u0467\u0467); Assert.Equal(5, obj.\u0467\u0467a); Assert.Equal(5, obj.\u0467\u0467b); Assert.Equal(6, obj.\u0467\u0467\u0467); Assert.Equal(7, obj.\u0467\u0467\u0467a); Assert.Equal(7, obj.\u0467\u0467\u0467b); Assert.Equal(8, obj.\u0467\u0467\u0467\u0467); Assert.Equal(9, obj.\u0467\u0467\u0467\u0467a); Assert.Equal(9, obj.\u0467\u0467\u0467\u0467b); } obj = new ClassWithPropertyNamePermutations { a = 1, aa = 2, aaa = 3, aaaa = 4, aaaaa = 5, aaaaaa = 6, aaaaaaa = 7, aaaaaab = 7, aaaaaaaa = 8, aaaaaaab = 8, aaaaaaaaa = 9, aaaaaaaab = 9, \u0467 = 2, \u0467\u0467 = 4, \u0467\u0467a = 5, \u0467\u0467b = 5, \u0467\u0467\u0467 = 6, \u0467\u0467\u0467a = 7, \u0467\u0467\u0467b = 7, \u0467\u0467\u0467\u0467 = 8, \u0467\u0467\u0467\u0467a = 9, \u0467\u0467\u0467\u0467b = 9, }; // Verify baseline. Verify(); string json = await JsonSerializerWrapperForString.SerializeWrapper(obj); // Verify the length is consistent with a verified value. Assert.Equal(354, json.Length); obj = await JsonSerializerWrapperForString.DeserializeWrapper <ClassWithPropertyNamePermutations>(json); // Verify round-tripped object. Verify(); }
public async Task ExtensionDataProperty_CannotBindTo_CtorParam() { InvalidOperationException ex = await Assert.ThrowsAsync <InvalidOperationException>(() => JsonSerializerWrapperForString.DeserializeWrapper <Class_ExtData_CtorParam>("{}")); string exStr = ex.ToString(); // System.InvalidOperationException: 'The extension data property 'ExtensionData' on type 'System.Text.Json.Serialization.Tests.ConstructorTests+Class_ExtData_CtorParam' cannot bind with a parameter in the deserialization constructor.' Assert.Contains("ExtensionData", exStr); Assert.Contains("System.Text.Json.Serialization.Tests.ConstructorTests+Class_ExtData_CtorParam", exStr); }
public async Task WriteImmutableCollectionWrappers() { SimpleTestClassWithIImmutableDictionaryWrapper obj1 = new SimpleTestClassWithIImmutableDictionaryWrapper(); SimpleTestClassWithImmutableListWrapper obj2 = new SimpleTestClassWithImmutableListWrapper(); SimpleTestClassWithImmutableStackWrapper obj3 = new SimpleTestClassWithImmutableStackWrapper(); SimpleTestClassWithImmutableQueueWrapper obj4 = new SimpleTestClassWithImmutableQueueWrapper(); SimpleTestClassWithImmutableSetWrapper obj5 = new SimpleTestClassWithImmutableSetWrapper(); obj1.Initialize(); obj2.Initialize(); obj3.Initialize(); obj4.Initialize(); obj5.Initialize(); Assert.Equal(SimpleTestClassWithIImmutableDictionaryWrapper.s_json.StripWhitespace(), await JsonSerializerWrapperForString.SerializeWrapper(obj1)); Assert.Equal(SimpleTestClassWithIImmutableDictionaryWrapper.s_json.StripWhitespace(), await JsonSerializerWrapperForString.SerializeWrapper <object>(obj1)); Assert.Equal(SimpleTestClassWithImmutableListWrapper.s_json.StripWhitespace(), await JsonSerializerWrapperForString.SerializeWrapper(obj2)); Assert.Equal(SimpleTestClassWithImmutableListWrapper.s_json.StripWhitespace(), await JsonSerializerWrapperForString.SerializeWrapper <object>(obj2)); Assert.Equal(SimpleTestClassWithImmutableStackWrapper.s_json.StripWhitespace(), await JsonSerializerWrapperForString.SerializeWrapper(obj3)); Assert.Equal(SimpleTestClassWithImmutableStackWrapper.s_json.StripWhitespace(), await JsonSerializerWrapperForString.SerializeWrapper <object>(obj3)); Assert.Equal(SimpleTestClassWithImmutableQueueWrapper.s_json.StripWhitespace(), await JsonSerializerWrapperForString.SerializeWrapper(obj4)); Assert.Equal(SimpleTestClassWithImmutableQueueWrapper.s_json.StripWhitespace(), await JsonSerializerWrapperForString.SerializeWrapper <object>(obj4)); Assert.Equal(SimpleTestClassWithImmutableSetWrapper.s_json.StripWhitespace(), await JsonSerializerWrapperForString.SerializeWrapper(obj5)); Assert.Equal(SimpleTestClassWithImmutableSetWrapper.s_json.StripWhitespace(), await JsonSerializerWrapperForString.SerializeWrapper <object>(obj5)); }
public MetadataTests(JsonSerializerWrapperForString serializer) { Serializer = serializer; }
public async Task UnicodeDictionaryKeys() { Dictionary <string, int> obj = new Dictionary <string, int> { { "A\u0467", 1 } }; // Verify the name is escaped after serialize. string json = await JsonSerializerWrapperForString.SerializeWrapper(obj, s_serializerOptionsPreserve); Assert.Equal(@"{""$id"":""1"",""A\u0467"":1}", json); // Round-trip Dictionary <string, int> objCopy = await JsonSerializerWrapperForString.DeserializeWrapper <Dictionary <string, int> >(json, s_serializerOptionsPreserve); Assert.Equal(1, objCopy["A\u0467"]); // Verify with encoder. var optionsWithEncoder = new JsonSerializerOptions { Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, ReferenceHandler = ReferenceHandler.Preserve }; json = await JsonSerializerWrapperForString.SerializeWrapper(obj, optionsWithEncoder); Assert.Equal("{\"$id\":\"1\",\"A\u0467\":1}", json); // Round-trip objCopy = await JsonSerializerWrapperForString.DeserializeWrapper <Dictionary <string, int> >(json, optionsWithEncoder); Assert.Equal(1, objCopy["A\u0467"]); // We want to go over StackallocByteThreshold=256 to force a pooled allocation, so this property is 200 chars and 400 bytes. const int charsInProperty = 200; string longPropertyName = new string('\u0467', charsInProperty); obj = new Dictionary <string, int> { { $"{longPropertyName}", 1 } }; Assert.Equal(1, obj[longPropertyName]); // Verify the name is escaped after serialize. json = await JsonSerializerWrapperForString.SerializeWrapper(obj, s_serializerOptionsPreserve); // Duplicate the unicode character 'charsInProperty' times. string longPropertyNameEscaped = new StringBuilder().Insert(0, @"\u0467", charsInProperty).ToString(); string expectedJson = $"{{\"$id\":\"1\",\"{longPropertyNameEscaped}\":1}}"; Assert.Equal(expectedJson, json); // Round-trip objCopy = await JsonSerializerWrapperForString.DeserializeWrapper <Dictionary <string, int> >(json, s_serializerOptionsPreserve); Assert.Equal(1, objCopy[longPropertyName]); // Verify the name is escaped after serialize. json = await JsonSerializerWrapperForString.SerializeWrapper(obj, optionsWithEncoder); // Duplicate the unicode character 'charsInProperty' times. longPropertyNameEscaped = new StringBuilder().Insert(0, "\u0467", charsInProperty).ToString(); expectedJson = $"{{\"$id\":\"1\",\"{longPropertyNameEscaped}\":1}}"; Assert.Equal(expectedJson, json); // Round-trip objCopy = await JsonSerializerWrapperForString.DeserializeWrapper <Dictionary <string, int> >(json, optionsWithEncoder); Assert.Equal(1, objCopy[longPropertyName]); }
public InvalidTypeTests(JsonSerializerWrapperForString serializer) { Serializer = serializer; }
public async Task ReadSimpleClassWithImmutableArray() { SimpleTestClassWithImmutableArray obj = await JsonSerializerWrapperForString.DeserializeWrapper <SimpleTestClassWithImmutableArray>(SimpleTestClassWithImmutableArray.s_json); obj.Verify(); }
public async Task VerifyValidationsOnPreservedReferenceOfTypeObject() { const string baseJson = @"{""Child"":{""$id"":""1""},""Sibling"":"; // A JSON object that contains a '$ref' metadata property must not contain any other properties. string testJson = baseJson + @"{""foo"":""value"",""$ref"":""1""}}"; JsonException ex = await Assert.ThrowsAsync <JsonException>(async() => await JsonSerializerWrapperForString.DeserializeWrapper <ClassWithObjectProperty>(testJson, s_serializerOptionsPreserve)); Assert.Equal("$.Sibling", ex.Path); testJson = baseJson + @"{""$ref"":""1"",""bar"":""value""}}"; ex = await Assert.ThrowsAsync <JsonException>(async() => await JsonSerializerWrapperForString.DeserializeWrapper <ClassWithObjectProperty>(testJson, s_serializerOptionsPreserve)); Assert.Equal("$.Sibling", ex.Path); // The '$id' and '$ref' metadata properties must be JSON strings. testJson = baseJson + @"{""$ref"":1}}"; ex = await Assert.ThrowsAsync <JsonException>(async() => await JsonSerializerWrapperForString.DeserializeWrapper <ClassWithObjectProperty>(testJson, s_serializerOptionsPreserve)); Assert.Equal("$.Sibling", ex.Path); }
public async Task WriteNestedAsyncEnumerableSync_ThrowsNotSupportedException() { IAsyncEnumerable <int> asyncEnumerable = new MockedAsyncEnumerable <int>(Enumerable.Range(1, 10)); await Assert.ThrowsAsync <NotSupportedException>(async() => await JsonSerializerWrapperForString.SerializeWrapper(new { Data = asyncEnumerable })); }