Json.NET is not deserializing my pretty object!

This stumped me for a while, so I figured I'd share. I had this type


    public struct ChangeNameEvent : IEvent
    {
        public string Name { get; private set; }
        public uint Id { get; private set; }

        public ChangeNameEvent(string name, uint id)
        {
            Name = name;
            Id = id;
        }
    }

... and this Unit Test ...


        [TestMethod]
        public void TestMethod4()
        {
            var serializationSettings = new JsonSerializerSettings
            {
                TypeNameHandling = TypeNameHandling.All
            };

            const string serializedObject = "{\"$type\":\"Domain.ChangeNameEvent, ProperDomani\",\"Name\":\"Admin\",\"Id\":42}";

            var evt = (IEvent)JsonConvert.DeserializeObject(
                serializedObject, serializationSettings);

            Assert.AreEqual(42u, evt.Id);
            Assert.IsInstanceOfType(evt, typeof(ChangeNameEvent));
            Assert.AreEqual("Admin", ((ChangeNameEvent)evt).Name);
        }

That showed everything working just fine. However, in my web application, my object came out with null valued properties. As it turns out, even if JsonNet have no problem calling the struct constructor in a unit test setting, it has issues doing the same in a web context. I haven't figured out why, but the fact remains. I fixed the issue by making my properties public:

    public struct ChangeNameEvent : IEvent
    {
        public string Name { get; private set; }
        public uint Id { get; private set; }

        public ChangeNameEvent(string name, uint id)
        {
            Name = name;
            Id = id;
        }
    }

Just thought you'd want to know 😉

Comments

Popular posts from this blog

Auto Mapper and Record Types - will they blend?

Unit testing your Azure functions - part 2: Queues and Blobs

Testing WCF services with user credentials and binary endpoints