コード例 #1
0
        public static void NullableValueTypedMemberWithNullsToInterfaceConverter()
        {
            const string expected = @"{""MyValueTypedProperty"":null,""MyRefTypedProperty"":null,""MyValueTypedField"":null,""MyRefTypedField"":null}";

            var converter = new ValueTypeToInterfaceConverter();
            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);
            }
        }
コード例 #2
0
        public static void AssignmentToValueTypedMemberInterface()
        {
            var converter = new ValueTypeToInterfaceConverter();
            var options   = new JsonSerializerOptions {
                IncludeFields = true
            };

            options.Converters.Add(converter);

            Exception ex;

            // Invalid cast OtherVTMember
            ex = Assert.Throws <InvalidCastException>(() => JsonSerializer.Deserialize <TestClassWithValueTypedMember>(@"{""MyValueTypedProperty"":""OtherVTProperty""}", options));
            ex = Assert.Throws <InvalidCastException>(() => JsonSerializer.Deserialize <TestClassWithValueTypedMember>(@"{""MyValueTypedField"":""OtherVTField""}", options));
            // Invalid cast OtherRTMember
            ex = Assert.Throws <InvalidCastException>(() => JsonSerializer.Deserialize <TestClassWithValueTypedMember>(@"{""MyValueTypedProperty"":""OtherRTProperty""}", options));
            ex = Assert.Throws <InvalidCastException>(() => JsonSerializer.Deserialize <TestClassWithValueTypedMember>(@"{""MyValueTypedField"":""OtherRTField""}", options));
            // Invalid null
            ex = Assert.Throws <InvalidOperationException>(() => JsonSerializer.Deserialize <TestClassWithValueTypedMember>(@"{""MyValueTypedProperty"":null}", options));
            ex = Assert.Throws <InvalidOperationException>(() => JsonSerializer.Deserialize <TestClassWithValueTypedMember>(@"{""MyValueTypedField"":null}", options));
        }