public void all_basic_types_roundtrip(PocoJsonSerializerMode mode) { var c = TestHelper.CreateStObjCollector(typeof(PocoJsonSerializer), typeof(IAllBasicTypes));; using var services = TestHelper.CreateAutomaticServices(c).Services; var directory = services.GetRequiredService <PocoDirectory>(); var nMax = services.GetRequiredService <IPocoFactory <IAllBasicTypes> >().Create(); nMax.PByte = Byte.MaxValue; nMax.PSByte = SByte.MaxValue; nMax.PShort = Int16.MaxValue; nMax.PUShort = UInt16.MaxValue; nMax.PInteger = Int32.MaxValue; nMax.PUInteger = UInt32.MaxValue; nMax.PLong = Int64.MaxValue; nMax.PULong = UInt64.MaxValue; nMax.PFloat = Single.MaxValue; nMax.PDouble = Double.MaxValue; nMax.PDecimal = Decimal.MaxValue; nMax.PBigInteger = BigInteger.Parse("12345678901234567890123456789012345678901234567890123456789012345678901234567890", System.Globalization.NumberFormatInfo.InvariantInfo); nMax.PDateTime = Util.UtcMaxValue; nMax.PDateTimeOffset = DateTimeOffset.MaxValue; nMax.PTimeSpan = TimeSpan.MaxValue; nMax.PGuid = Guid.Parse("ffffffff-ffff-ffff-ffff-ffffffffffff"); var nMin = services.GetRequiredService <IPocoFactory <IAllBasicTypes> >().Create(); nMin.PByte = Byte.MinValue; nMin.PSByte = SByte.MinValue; nMin.PShort = Int16.MinValue; nMin.PUShort = UInt16.MinValue; nMin.PInteger = Int32.MinValue; nMin.PUInteger = UInt32.MinValue; nMin.PLong = Int64.MinValue; nMin.PULong = UInt64.MinValue; nMin.PFloat = Single.MinValue; nMin.PDouble = Double.MinValue; nMin.PDecimal = Decimal.MinValue; nMin.PBigInteger = BigInteger.Parse("-12345678901234567890123456789012345678901234567890123456789012345678901234567890", System.Globalization.NumberFormatInfo.InvariantInfo); nMin.PDateTime = Util.UtcMinValue; nMin.PDateTimeOffset = DateTimeOffset.MinValue; nMin.PTimeSpan = TimeSpan.MinValue; nMin.PGuid = Guid.Empty; var options = new PocoJsonSerializerOptions { Mode = mode }; var nMax2 = JsonTestHelper.Roundtrip(directory, nMax, options, text: t => TestHelper.Monitor.Info($"IAllBasicTypes(max) serialization: " + t)); nMax2.Should().BeEquivalentTo(nMax); var nMin2 = JsonTestHelper.Roundtrip(directory, nMin, options, text: t => TestHelper.Monitor.Info($"IAllBasicTypes(min) serialization: " + t)); nMin2.Should().BeEquivalentTo(nMin); }
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 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()); } }
public static void ParseNullStringToStructShouldThrowJsonException() { string nullString = "null"; Utf8JsonReader reader = new Utf8JsonReader(Encoding.UTF8.GetBytes(nullString)); JsonTestHelper.AssertThrows <JsonException>(reader, (reader) => JsonSerializer.Deserialize <SimpleStruct>(ref reader)); Assert.Throws <JsonException>(() => JsonSerializer.Deserialize <SimpleStruct>(Encoding.UTF8.GetBytes(nullString))); Assert.Throws <JsonException>(() => JsonSerializer.Deserialize <SimpleStruct>(nullString)); }
public override void ParameterizedConstructor() { string json = JsonSerializer.Serialize(new HighLowTempsImmutable(1, 2), DefaultContext.HighLowTempsImmutable); Assert.Contains(@"""High"":1", json); Assert.Contains(@"""Low"":2", json); JsonTestHelper.AssertThrows_PropMetadataInit(() => JsonSerializer.Deserialize(json, DefaultContext.HighLowTempsImmutable), typeof(HighLowTempsImmutable)); }
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 override void RoundTripIndexViewModel() { IndexViewModel expected = CreateIndexViewModel(); string json = JsonSerializer.Serialize(expected, DefaultContext.IndexViewModel); JsonTestHelper.AssertThrows_PropMetadataInit(() => JsonSerializer.Deserialize(json, DefaultContext.IndexViewModel), typeof(CampaignSummaryViewModel)); IndexViewModel obj = JsonSerializer.Deserialize(json, ((ITestContext)MetadataWithPerTypeAttributeContext.Default).IndexViewModel); VerifyIndexViewModel(expected, obj); }
public override void RoundTripCollectionsDictionary() { WeatherForecastWithPOCOs expected = CreateWeatherForecastWithPOCOs(); string json = JsonSerializer.Serialize(expected, DefaultContext.WeatherForecastWithPOCOs); JsonTestHelper.AssertThrows_PropMetadataInit(() => JsonSerializer.Deserialize(json, DefaultContext.WeatherForecastWithPOCOs), typeof(HighLowTemps)); WeatherForecastWithPOCOs obj = JsonSerializer.Deserialize(json, ((ITestContext)MetadataWithPerTypeAttributeContext.Default).WeatherForecastWithPOCOs); VerifyWeatherForecastWithPOCOs(expected, obj); }
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 override void RoundTripTypeNameClash() { RepeatedTypes.Location expected = CreateRepeatedLocation(); string json = JsonSerializer.Serialize(expected, DefaultContext.RepeatedLocation); JsonTestHelper.AssertThrows_PropMetadataInit(() => JsonSerializer.Deserialize(json, DefaultContext.RepeatedLocation), typeof(RepeatedTypes.Location)); RepeatedTypes.Location obj = JsonSerializer.Deserialize(json, ((ITestContext)MetadataWithPerTypeAttributeContext.Default).RepeatedLocation); VerifyRepeatedLocation(expected, obj); AssertFastPathLogicCorrect(json, obj, DefaultContext.RepeatedLocation); }
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 void simple_poco_serialization() { var c = TestHelper.CreateStObjCollector(typeof(PocoJsonSerializer), typeof(ITest));; using var s = TestHelper.CreateAutomaticServices(c).Services; var directory = s.GetRequiredService <PocoDirectory>(); var f = s.GetRequiredService <IPocoFactory <ITest> >(); var o = f.Create(o => { o.Power = 3712; o.Hip += "CodeGen!"; }); var o2 = JsonTestHelper.Roundtrip(directory, o); o2.Power.Should().Be(o.Power); o2.Hip.Should().Be(o.Hip); }
public override void RoundTripLocation() { Location expected = CreateLocation(); string json = JsonSerializer.Serialize(expected, DefaultContext.Location); JsonTestHelper.AssertThrows_PropMetadataInit(() => JsonSerializer.Deserialize(json, DefaultContext.Location), typeof(Location)); Location obj = JsonSerializer.Deserialize(json, ((ITestContext)MetadataContext.Default).Location); VerifyLocation(expected, obj); AssertFastPathLogicCorrect(json, obj, DefaultContext.Location); }
public override void RoundTripNumberTypes() { NumberTypes expected = CreateNumberTypes(); string json = JsonSerializer.Serialize(expected, DefaultContext.NumberTypes); JsonTestHelper.AssertThrows_PropMetadataInit(() => JsonSerializer.Deserialize(json, DefaultContext.NumberTypes), typeof(NumberTypes)); NumberTypes obj = JsonSerializer.Deserialize(json, ((ITestContext)MetadataWithPerTypeAttributeContext.Default).NumberTypes); VerifyNumberTypes(expected, obj); AssertFastPathLogicCorrect(json, obj, DefaultContext.NumberTypes); }
public override void RoundTripActiveOrUpcomingEvent() { ActiveOrUpcomingEvent expected = CreateActiveOrUpcomingEvent(); string json = JsonSerializer.Serialize(expected, DefaultContext.ActiveOrUpcomingEvent); JsonTestHelper.AssertThrows_PropMetadataInit(() => JsonSerializer.Deserialize(json, DefaultContext.ActiveOrUpcomingEvent), typeof(ActiveOrUpcomingEvent)); ActiveOrUpcomingEvent obj = JsonSerializer.Deserialize(json, ((ITestContext)MetadataWithPerTypeAttributeContext.Default).ActiveOrUpcomingEvent); VerifyActiveOrUpcomingEvent(expected, obj); AssertFastPathLogicCorrect(json, obj, DefaultContext.ActiveOrUpcomingEvent); }
public override void RoundTripIndexViewModel() { IndexViewModel expected = CreateIndexViewModel(); string json = JsonSerializer.Serialize(expected, DefaultContext.IndexViewModel); JsonTestHelper.AssertThrows_PropMetadataInit(() => JsonSerializer.Deserialize(json, DefaultContext.IndexViewModel), typeof(IndexViewModel)); IndexViewModel obj = JsonSerializer.Deserialize(json, ((ITestContext)MetadataContext.Default).IndexViewModel); VerifyIndexViewModel(expected, obj); AssertFastPathLogicCorrect(json, obj, DefaultContext.IndexViewModel); }
public override void RoundTripEmptyPoco() { EmptyPoco expected = CreateEmptyPoco(); string json = JsonSerializer.Serialize(expected, DefaultContext.EmptyPoco); JsonTestHelper.AssertThrows_PropMetadataInit(() => JsonSerializer.Deserialize(json, DefaultContext.EmptyPoco), typeof(EmptyPoco)); EmptyPoco obj = JsonSerializer.Deserialize(json, ((ITestContext)MetadataWithPerTypeAttributeContext.Default).EmptyPoco); VerifyEmptyPoco(expected, obj); AssertFastPathLogicCorrect(json, obj, DefaultContext.EmptyPoco); }
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 void null_poco_is_handled() { var c = TestHelper.CreateStObjCollector(typeof(PocoJsonSerializer), typeof(ITest));; using var s = TestHelper.CreateAutomaticServices(c).Services; var directory = s.GetRequiredService <PocoDirectory>(); ITest?nullPoco = null; JsonTestHelper.Roundtrip(directory, nullPoco).Should().BeNull(); IPoco?nullUnknwonPoco = null; JsonTestHelper.Roundtrip(directory, nullUnknwonPoco).Should().BeNull(); }
public void list_of_list_serialization() { var c = TestHelper.CreateStObjCollector(typeof(PocoJsonSerializer), typeof(IListOfList)); using var s = TestHelper.CreateAutomaticServices(c).Services; var directory = s.GetRequiredService <PocoDirectory>(); var f = s.GetRequiredService <IPocoFactory <IListOfList> >(); var oD = f.Create(o => { o.List.Add(new List <int> { 1, 2 }); }); var oD2 = JsonTestHelper.Roundtrip(directory, oD); oD2.List[0].Should().HaveCount(2); }
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 async Task CompareResultsAgainstSerializer() { List <Order> obj = JsonTestHelper.PopulateLargeObject(2); string expected = await Serializer.SerializeWrapper(obj); JsonArray jArray = await Serializer.DeserializeWrapper <JsonArray>(expected); string actual = jArray.ToJsonString(); Assert.Equal(expected, actual); jArray = JsonNode.Parse(expected).AsArray(); actual = jArray.ToJsonString(); Assert.Equal(expected, actual); }
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 static void ParseNullStringToStructShouldThrowJsonException() { string nullString = "null"; byte[] nullStringAsBytes = Encoding.UTF8.GetBytes(nullString); Utf8JsonReader reader = new Utf8JsonReader(nullStringAsBytes); JsonTestHelper.AssertThrows <JsonException>(ref reader, (ref Utf8JsonReader reader) => JsonSerializer.Deserialize <SimpleStruct>(ref reader)); Assert.Throws <JsonException>(() => JsonSerializer.Deserialize <SimpleStruct>(nullStringAsBytes)); Assert.Throws <JsonException>(() => JsonSerializer.Deserialize <SimpleStruct>(nullString)); // null can be assigned to nullable structs. Assert.Null(JsonSerializer.Deserialize <SimpleStruct?>(nullStringAsBytes)); Assert.Null(JsonSerializer.Deserialize <SimpleStruct?>(nullString)); }
public static void SerializationFuncNotInvokedWhenNotSupported(JsonSerializerOptions options) { JsonMessage message = new(); // Per context implementation, NotImplementedException thrown because the options are compatible, hence the serialization func is invoked. Assert.Throws <NotImplementedException>(() => JsonSerializer.Serialize(message, JsonContext.Default.JsonMessage)); Assert.Throws <NotImplementedException>(() => JsonSerializer.Serialize(message, typeof(JsonMessage), JsonContext.Default)); // NotSupportedException thrown because // - the options are not compatible, hence the serialization func is not invoked. // - the serializer correctly tries to serialize based on property metadata, but we have not provided it in our implementation. JsonContext context = new(options); JsonTestHelper.AssertThrows_PropMetadataInit(() => JsonSerializer.Serialize(message, context.JsonMessage), typeof(JsonMessage)); JsonTestHelper.AssertThrows_PropMetadataInit(() => JsonSerializer.Serialize(message, typeof(JsonMessage), context), typeof(JsonMessage)); }
public void basic_types_properties_as_Object_are_supported() { var c = TestHelper.CreateStObjCollector(typeof(PocoJsonSerializer), typeof(IPocoWithObject)); using var s = TestHelper.CreateAutomaticServices(c).Services; var directory = s.GetRequiredService <PocoDirectory>(); var f = s.GetRequiredService <IPocoFactory <IPocoWithObject> >(); var a = f.Create(a => { a.Value = 1; }); var a2 = JsonTestHelper.Roundtrip(directory, a); a2.Should().BeEquivalentTo(a); }