NewtonSoft JSON.NET update implicitly serializes protected members

I just upgraded my version of NewtonSoft JSON.NET from version 3.0.0 to 3.5.0, and I noticed that the protected members are implicitly serialized.

I have the following class:

public class SimpleFileContainer : IDto { public virtual string Name { get; protected set; } public virtual string Path { get; protected set; } public SimpleFileContainer(string name, string path) { Name = name; Path = path; } } 

The following test code fails

 var json = JsonConvert.SerializeObject(new SimpleFileContainer("Name", "Path")); var deserialised = JsonConvert.DeserializeObject<SimpleFileContainer >(json); Assert.That(deserialised.Name, Is.EqualTo("Name"); 

both the Name and Path properties are null unless I make the property sets public or add a class update with the following attributes:

 [JsonObject(MemberSerialization.OptOut)] public class SimpleFileContainer : IDto { [JsonProperty] public virtual string Name { get; protected set; } [JsonProperty] public virtual string Path { get; protected set; } public SimpleFileContainer(string name, string path) { Name = name; Path = path; } } 

This is a project with a reasonable size, which uses the serialization process a lot, I donโ€™t want to go through the code, adding these attributes to each class and member.

Is there any way around this?

+4
source share
1 answer

I had the same problem today. Fortunately, Ayende corrected, and I am sharing with you. When you configure the serializer, change the DefaultMembersSearchFlags property to ContractResolver:

 var serializer = new JsonSerializer { ReferenceLoopHandling = ReferenceLoopHandling.Ignore, ContractResolver = new DefaultContractResolver { DefaultMembersSearchFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance }, TypeNameAssemblyFormat = FormatterAssemblyStyle.Simple, ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor }; 
+7
source

Source: https://habr.com/ru/post/1313503/


All Articles