JSON deserialize to constructed protected setter array
Mark Outs
with the [JsonProperty]
attribute:
private class Engine
{
public string Text { get; set; }
public int Id { get; set; }
[JsonProperty] // Causes the protected setter to be called on deserialization.
public Coords[] Outs { get; protected set; }
public Engine()
{
this.Outs = new Coords[3];
for (int i = 0; i < this.Outs.Length; i++)
{
this.Outs[i] = new Coords();
}
}
}
Try this:
var contractResolver = new DefaultContractResolver();
contractResolver.DefaultMembersSearchFlags |= BindingFlags.NonPublic;
Engine r = JsonConvert.DeserializeObject<Engine>(json), new JsonSerializerSettings
{
ContractResolver = contractResolver
});
Using above-mentioned code you will get the follwoing Warning message:
'DefaultContractResolver.DefaultMembersSearchFlags' is obsolete: 'DefaultMembersSearchFlags is obsolete. To modify the members serialized inherit from DefaultContractResolver and override the GetSerializableMembers method instead.'
To solve it you can use the following solution instead:
Create a class that inherits from DefaultContractResolver
to get the non public properties:
public class CustomContractResolver : DefaultContractResolver
{
protected override JsonProperty CreateProperty(
MemberInfo member,
MemberSerialization memberSerialization)
{
var prop = base.CreateProperty(member, memberSerialization);
if (!prop.Writable)
{
var property = member as PropertyInfo;
if (property != null)
{
var hasNonPublicSetter = property.GetSetMethod(true) != null;
prop.Writable = hasNonPublicSetter;
}
}
return prop;
}
}
And finally use it as follow:
var contractResolver = new CustomContractResolver();
Engine r = JsonConvert.DeserializeObject<Engine>(json), new JsonSerializerSettings
{
ContractResolver = contractResolver
});