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); } }
public static void AssignmentToValueTypedMemberObject() { var converter = new ValueTypeToObjectConverter(); 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)); }