Suppose I have the following class -
public class A
{
public int P1 { get; internal set; }
}
Using json.net, I am able to serialize the type with P1 property. However, during deserialization, P1 is not set. Without modifying class A, is there an in build way to handle this? In my case, I am using a class from a different assembly and cannot modify it.
Yes, you can use a custom ContractResolver
to make the internal property writable to Json.Net. Here is the code you would need:
class CustomResolver : DefaultContractResolver
{
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
JsonProperty prop = base.CreateProperty(member, memberSerialization);
if (member.DeclaringType == typeof(A) && prop.PropertyName == "P1")
{
prop.Writable = true;
}
return prop;
}
}
To use the resolver, create an instance of JsonSerializerSettings
and set its ContractResolver
property to a new instance of the custom resolver. Then, pass the settings to JsonConvert.DeserializeObject<T>()
.
Demo:
class Program
{
static void Main(string[] args)
{
string json = @"{ ""P1"" : ""42"" }";
JsonSerializerSettings settings = new JsonSerializerSettings();
settings.ContractResolver = new CustomResolver();
A a = JsonConvert.DeserializeObject<A>(json, settings);
Console.WriteLine(a.P1);
}
}
Output:
42
Fiddle: https://dotnetfiddle.net/1fw2lC
After some experimenting, I've found that a property is deserialised correctly if you decorate your property with:
[JsonProperty(DefaultValueHandling = DefaultValueHandling.Include)]
Applying to the class in the original question:
public class A
{
[JsonProperty(DefaultValueHandling = DefaultValueHandling.Include)]
public int P1 { get; internal set; }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With