private IDiscriminatorConvention?InternalGetConvention(Type type)
        {
            IDiscriminatorConvention?convention = _conventions.FirstOrDefault(c => c.TryRegisterType(type));

            if (convention != null)
            {
                IObjectMapping objectMapping = _options.GetObjectMappingRegistry().Lookup(type);
                objectMapping.AddDiscriminatorMapping();

                // setup discriminator for all base types
                for (Type?currentType = type.BaseType; currentType != null && currentType != typeof(object); currentType = currentType.BaseType)
                {
                    objectMapping = _options.GetObjectMappingRegistry().Lookup(currentType);
                    objectMapping.AddDiscriminatorMapping();
                    _conventionsByType.TryAdd(currentType, convention);
                }

                // setup discriminator for all interfaces
                foreach (Type @interface in type.GetInterfaces())
                {
                    _conventionsByType.TryAdd(@interface, convention);
                }
            }

            return(convention);
        }
Example #2
0
        public void WriteWithMapMember()
        {
            JsonSerializerOptions options = new JsonSerializerOptions();

            options.SetupExtensions();
            options.GetObjectMappingRegistry().Register <SimpleObject>(objectMapping =>
                                                                       objectMapping
                                                                       .AutoMap()
                                                                       .ClearMemberMappings()
                                                                       .MapMember(o => o.Boolean)
                                                                       );

            SimpleObject obj = new SimpleObject
            {
                Boolean  = true,
                Byte     = 12,
                SByte    = 13,
                Int16    = 14,
                UInt16   = 15,
                Int32    = 16,
                UInt32   = 17u,
                Int64    = 18,
                UInt64   = 19ul,
                Single   = 20.21f,
                Double   = 22.23,
                String   = "string",
                DateTime = new DateTime(2014, 02, 21, 19, 0, 0, DateTimeKind.Utc),
                Enum     = EnumTest.Value1
            };

            const string json = @"{""Boolean"":true}";

            Helper.TestWrite(obj, json, options);
        }
Example #3
0
        public void ReadWithMapMember()
        {
            JsonSerializerOptions options = new JsonSerializerOptions();

            options.SetupExtensions();
            options.GetObjectMappingRegistry().Register <SimpleObject>(objectMapping =>
                                                                       objectMapping
                                                                       .AutoMap()
                                                                       .ClearMemberMappings()
                                                                       .MapMember(o => o.Boolean)
                                                                       );

            const string json = @"{""Boolean"":true,""SByte"":13,""Byte"":12,""Int16"":14,""UInt16"":15,""Int32"":16,""UInt32"":17,""Int64"":18,""UInt64"":19,""String"":""string"",""Single"":20.209999084472656,""Double"":22.23,""DateTime"":""2014-02-21T19:00:00Z"",""Enum"":""Value1""}";
            SimpleObject obj  = Helper.Read <SimpleObject>(json, options);

            Assert.NotNull(obj);
            Assert.True(obj.Boolean);
            Assert.Equal(0, obj.Byte);
            Assert.Equal(0, obj.SByte);
            Assert.Equal(0, obj.Int16);
            Assert.Equal(0, obj.UInt16);
            Assert.Equal(0, obj.Int32);
            Assert.Equal(0u, obj.UInt32);
            Assert.Equal(0L, obj.Int64);
            Assert.Equal(0ul, obj.UInt64);
            Assert.Equal(0f, obj.Single);
            Assert.Equal(0.0, obj.Double);
            Assert.Null(obj.String);
            Assert.Equal(DateTime.MinValue, obj.DateTime);
            Assert.Equal(EnumTest.None, obj.Enum);
        }
Example #4
0
        public void WriteValueByApi()
        {
            JsonSerializerOptions options = new JsonSerializerOptions();

            options.SetupExtensions();
            options.GetObjectMappingRegistry().Register <ObjectWithDefaultValue2>(objectMapping =>
            {
                objectMapping.AutoMap();
                objectMapping.ClearMemberMappings();
                objectMapping.MapMember(o => o.Id).SetDefaultValue(12).SetIgnoreIfDefault(true);
                objectMapping.MapMember(o => o.FirstName).SetDefaultValue("foo").SetIgnoreIfDefault(true);
                objectMapping.MapMember(o => o.LastName).SetDefaultValue("foo").SetIgnoreIfDefault(true);
                objectMapping.MapMember(o => o.Age).SetDefaultValue(12).SetIgnoreIfDefault(true);
            });

            ObjectWithDefaultValue2 obj = new ObjectWithDefaultValue2
            {
                Id        = 13,
                FirstName = "foo",
                LastName  = "bar",
                Age       = 12
            };

            const string json = @"{""Id"":13,""LastName"":""bar""}";

            Helper.TestWrite(obj, json, options);
        }
Example #5
0
        public ObjectConverter(JsonSerializerOptions options)
        {
            _objectMapping    = options.GetObjectMappingRegistry().Lookup <T>();
            _memberConverters = new Lazy <MemberConverters>(() => MemberConverters.Create(options, _objectMapping));

            _isInterfaceOrAbstract = typeof(T).IsInterface || typeof(T).IsAbstract;
            _isStruct = typeof(T).IsStruct();

            if (!_isInterfaceOrAbstract && _objectMapping.CreatorMapping == null && !_isStruct)
            {
                ConstructorInfo defaultConstructorInfo = typeof(T).GetConstructor(
                    BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance,
                    null,
                    Type.EmptyTypes,
                    null);

                if (defaultConstructorInfo == null)
                {
                    throw new JsonException($"Cannot find a default constructor on type {typeof(T)}");
                }

                _constructor = defaultConstructorInfo.CreateDelegate <T>();
            }

            _discriminatorConvention = options.GetDiscriminatorConventionRegistry().GetConvention(typeof(T));
            _referenceHandling       = _isStruct ? ReferenceHandling.Default : options.GetReferenceHandling();
        }
Example #6
0
        public void Test()
        {
            var options = new JsonSerializerOptions().SetupExtensions();

            options.GetObjectMappingRegistry().Register <Car>(objectMapping =>
                                                              objectMapping
                                                              .AutoMap()
                                                              .SetCreatorMapping(null)
                                                              );
            var jsonString = JsonSerializer.Serialize(new Car("red", "4"), options);
        }
        public bool TryRegisterType(Type type)
        {
            IObjectMapping objectMapping = _options.GetObjectMappingRegistry().Lookup(type);

            if (objectMapping.Discriminator == null || !(objectMapping.Discriminator is T discriminator))
            {
                return(false);
            }

            _discriminatorsByType[type] = discriminator;
            _typesByDiscriminator.Add(discriminator, type);
            return(true);
        }
        public void TestRead(RequirementPolicy requirementPolicy, string json, Type expectedExceptionType)
        {
            JsonSerializerOptions options = new JsonSerializerOptions();

            options.SetupExtensions();
            options.GetObjectMappingRegistry().Register <StringObject>(objectMapping =>
                                                                       objectMapping
                                                                       .AutoMap()
                                                                       .ClearMemberMappings()
                                                                       .MapMember(o => o.String).SetRequired(requirementPolicy)
                                                                       );

            Helper.TestRead <StringObject>(json, options, expectedExceptionType);
        }
Example #9
0
        public void ReadWithNamingPolicy()
        {
            JsonSerializerOptions options = new JsonSerializerOptions();

            options.SetupExtensions();
            options.GetObjectMappingRegistry().Register <IntObject>(objectMapping =>
                                                                    objectMapping
                                                                    .AutoMap()
                                                                    .SetPropertyNamingPolicy(JsonNamingPolicy.CamelCase)
                                                                    );

            const string json = @"{""intValue"":12}";
            IntObject    obj  = Helper.Read <IntObject>(json, options);

            Assert.NotNull(obj);
            Assert.Equal(12, obj.IntValue);
        }
Example #10
0
        public void ConstructorByApi(string json, int expectedId, string expectedName, int expectedAge)
        {
            JsonSerializerOptions options = new JsonSerializerOptions();

            options.SetupExtensions();
            options.GetObjectMappingRegistry().Register <ObjectWithConstructor>(objectMapping =>
                                                                                objectMapping
                                                                                .AutoMap()
                                                                                .MapCreator(o => new ObjectWithConstructor(o.Id, o.Name))
                                                                                );

            ObjectWithConstructor obj = Helper.Read <ObjectWithConstructor>(json, options);

            Assert.NotNull(obj);
            Assert.Equal(expectedId, obj.Id);
            Assert.Equal(expectedName, obj.Name);
            Assert.Equal(expectedAge, obj.Age);
        }
Example #11
0
        public void TestWriteByApi()
        {
            JsonSerializerOptions options = new JsonSerializerOptions();

            options.SetupExtensions();
            options.GetObjectMappingRegistry().Register <ObjectWithCallbacks>(om =>
            {
                om.MapMember(o => o.Id);
                om.SetOnSerializingMethod(o => o.OnSerializing());
                om.SetOnSerializedMethod(o => o.OnSerialized());
            });

            const string json = @"{""Id"":12}";

            Helper.TestWrite(new ObjectWithCallbacks {
                Id = 12
            }, json, options);
        }
Example #12
0
        public void ReadWithMemberNameAndConverter()
        {
            JsonSerializerOptions options = new JsonSerializerOptions();

            options.SetupExtensions();
            options.GetObjectMappingRegistry().Register <ObjectWithGuid>(objectMapping =>
                                                                         objectMapping
                                                                         .AutoMap()
                                                                         .ClearMemberMappings()
                                                                         .MapMember(o => o.Guid)
                                                                         .SetConverter(new GuidConverter())
                                                                         .SetMemberName("g")
                                                                         );

            const string   json = @"{""g"":""e933aae2d74942aeb8628ac805df082f""}";
            ObjectWithGuid obj  = Helper.Read <ObjectWithGuid>(json, options);

            Assert.NotNull(obj);
            Assert.Equal(Guid.Parse("E933AAE2-D749-42AE-B862-8AC805DF082F"), obj.Guid);
        }
Example #13
0
        public void TestCustomMethod(int id, string json)
        {
            JsonSerializerOptions options = new JsonSerializerOptions();

            options.SetupExtensions();
            options.GetObjectMappingRegistry().Register <ObjectWithShouldSerialize2>(objectMapping =>
                                                                                     objectMapping
                                                                                     .AutoMap()
                                                                                     .ClearMemberMappings()
                                                                                     .MapMember(o => o.Id)
                                                                                     .SetShouldSerializeMethod(o => ((ObjectWithShouldSerialize2)o).Id != 12)
                                                                                     );

            ObjectWithShouldSerialize2 obj = new ObjectWithShouldSerialize2
            {
                Id = id
            };

            Helper.TestWrite(obj, json, options);
        }
Example #14
0
        public void WriteWithNamingPolicy()
        {
            JsonSerializerOptions options = new JsonSerializerOptions();

            options.SetupExtensions();
            options.GetObjectMappingRegistry().Register <IntObject>(objectMapping =>
                                                                    objectMapping
                                                                    .AutoMap()
                                                                    .SetPropertyNamingPolicy(JsonNamingPolicy.CamelCase)
                                                                    );

            IntObject obj = new IntObject
            {
                IntValue = 12
            };

            const string json = @"{""intValue"":12}";

            Helper.TestWrite(obj, json, options);
        }
Example #15
0
        public void TestReadByApi()
        {
            JsonSerializerOptions options = new JsonSerializerOptions();

            options.SetupExtensions();
            options.GetObjectMappingRegistry().Register <ObjectWithCallbacks>(om =>
            {
                om.MapMember(o => o.Id);
                om.SetOnDeserializingMethod(o => o.OnDeserializing());
                om.SetOnDeserializedMethod(o => o.OnDeserialized());
            });

            const string        json = @"{""Id"":12}";
            ObjectWithCallbacks obj  = Helper.Read <ObjectWithCallbacks>(json, options);

            Assert.NotNull(obj);
            Assert.True(obj.OnDeserializingCalled);
            Assert.True(obj.OnDeserializedCalled);
            Assert.False(obj.OnSerializingCalled);
            Assert.False(obj.OnSerializedCalled);
        }
Example #16
0
        public void FactoryByApi(string json, int expectedId, string expectedName, int expectedAge)
        {
            Factory factory = new Factory();
            Func <int, string, ObjectWithConstructor> creatorFunc = (int id, string name) => factory.NewObjectWithConstructor(id, name);

            JsonSerializerOptions options = new JsonSerializerOptions();

            options.SetupExtensions();
            options.GetObjectMappingRegistry().Register <ObjectWithConstructor>(objectMapping =>
                                                                                objectMapping
                                                                                .AutoMap()
                                                                                .MapCreator(creatorFunc)
                                                                                );

            ObjectWithConstructor obj = Helper.Read <ObjectWithConstructor>(json, options);

            Assert.NotNull(obj);
            Assert.Equal(expectedId, obj.Id);
            Assert.Equal(expectedName, obj.Name);
            Assert.Equal(expectedAge, obj.Age);
        }
Example #17
0
        public void Interface()
        {
            JsonSerializerOptions options = new JsonSerializerOptions();

            options.SetupExtensions();
            options.GetObjectMappingRegistry().Register <IFoo>(objectMapping =>
                                                               objectMapping
                                                               .AutoMap()
                                                               .MapCreator(o => new Foo())
                                                               );

            const string        json = @"{""Foo"":{""Id"":12}}";
            ObjectWithInterface obj  = Helper.Read <ObjectWithInterface>(json, options);

            Assert.NotNull(obj);
            Assert.NotNull(obj.Foo);
            Assert.IsType <Foo>(obj.Foo);
            Assert.Equal(12, obj.Foo.Id);

            Helper.TestWrite(obj, json, options);
        }
Example #18
0
        public void ReadWithDiscriminator()
        {
            JsonSerializerOptions options = new JsonSerializerOptions();

            options.SetupExtensions();
            options.GetDiscriminatorConventionRegistry().RegisterConvention(
                new AttributeBasedDiscriminatorConvention <string>(options, "_t"));
            options.GetObjectMappingRegistry().Register <InheritedObject>(objectMapping =>
                                                                          objectMapping
                                                                          .AutoMap()
                                                                          .SetDiscriminator("inherited")
                                                                          );

            const string json = @"{""_t"":""inherited"",""InheritedValue"":13,""BaseValue"":12}";
            BaseObject   obj  = Helper.Read <BaseObject>(json, options);

            Assert.NotNull(obj);
            Assert.IsType <InheritedObject>(obj);
            Assert.Equal(12, obj.BaseValue);
            Assert.Equal(13, ((InheritedObject)obj).InheritedValue);
        }
Example #19
0
        public void AbstractClass()
        {
            JsonSerializerOptions options = new JsonSerializerOptions();

            options.SetupExtensions();
            options.GetObjectMappingRegistry().Register <AbstractBar>(objectMapping =>
                                                                      objectMapping
                                                                      .AutoMap()
                                                                      .MapCreator(o => new Bar())
                                                                      );

            const string            json = @"{""Bar"":{""Id"":12}}";
            ObjectWithAbstractClass obj  = Helper.Read <ObjectWithAbstractClass>(json, options);

            Assert.NotNull(obj);
            Assert.NotNull(obj.Bar);
            Assert.IsType <Bar>(obj.Bar);
            Assert.Equal(12, obj.Bar.Id);

            Helper.TestWrite(obj, json, options);
        }
        public void TestWriteByApi()
        {
            JsonSerializerOptions options = new JsonSerializerOptions();

            options.SetupExtensions();
            options.GetObjectMappingRegistry().Register <Tree>(objectMapping =>
            {
                objectMapping.AutoMap();
                objectMapping.ClearMemberMappings();
                objectMapping.MapMember(
                    typeof(Tree)
                    .GetField(nameof(Tree.Id), BindingFlags.Public | BindingFlags.Static),
                    typeof(string));
                objectMapping.MapMember(tree => tree.Name);
                objectMapping.MapMember(tree => Tree.WhatEver);
            });

            Tree         obj  = new Tree();
            const string json = @"{""Id"":""Tree.class"",""Name"":""LemonTree"",""WhatEver"":12}";

            Helper.TestWrite(obj, json, options);
        }
Example #21
0
        public void WriteWithDiscriminator()
        {
            JsonSerializerOptions options = new JsonSerializerOptions();

            options.SetupExtensions();
            options.GetDiscriminatorConventionRegistry().RegisterConvention(
                new AttributeBasedDiscriminatorConvention <string>(options, "_t"));
            options.GetObjectMappingRegistry().Register <InheritedObject>(objectMapping =>
                                                                          objectMapping
                                                                          .SetDiscriminator("inherited")
                                                                          .AutoMap()
                                                                          );

            InheritedObject obj = new InheritedObject
            {
                BaseValue      = 12,
                InheritedValue = 13
            };

            const string json = @"{""_t"":""inherited"",""InheritedValue"":13,""BaseValue"":12}";

            Helper.TestWrite <BaseObject>(obj, json, options);
        }
Example #22
0
        public void WriteWithMemberNameAndConverter()
        {
            JsonSerializerOptions options = new JsonSerializerOptions();

            options.SetupExtensions();
            options.GetObjectMappingRegistry().Register <ObjectWithGuid>(objectMapping =>
                                                                         objectMapping
                                                                         .AutoMap()
                                                                         .ClearMemberMappings()
                                                                         .MapMember(o => o.Guid)
                                                                         .SetConverter(new GuidConverter())
                                                                         .SetMemberName("g")
                                                                         );

            ObjectWithGuid obj = new ObjectWithGuid
            {
                Guid = Guid.Parse("E933AAE2-D749-42AE-B862-8AC805DF082F")
            };

            const string json = @"{""g"":""e933aae2d74942aeb8628ac805df082f""}";

            Helper.TestWrite(obj, json, options);
        }