You could pass the NullValueHandling
flag to the JsonProperty
attribute if you're using Newtonsoft. Here's an example in their documentation:
https://www.newtonsoft.com/json/help/html/JsonPropertyPropertyLevelSetting.htm
Edit
Try creating the following object structure:
public class Person
{
public string Email { get; set; }
public DateTime CreatedDate { get; set; }
public List<Role> Roles { get; set; }
}
public class Role
{
public string name { get; set; }
public string type { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string town { get; set; }
}
Then copy that json into a file and deserialize like this
string json = File.ReadAllText("a.json");
Person person = JsonConvert.DeserializeObject<Person>(json);
Edit
Well, if you really don't want to see that property at all, you're going to end up with some ugly code. Here's a quick and dirty example that works.
public class PersonA
{
public string Email { get; set; }
public DateTime CreatedDate { get; set; }
public List<RoleB> Roles { get; set; }
}
public class RoleB : RoleA
{
public string town { get; set; }
}
public class PersonB
{
public string Email { get; set; }
public DateTime CreatedDate { get; set; }
public List<RoleA> RolesA { get; set; } = new List<RoleA>();
public List<RoleB> RolesB { get; set; } = new List<RoleB>();
}
public class RoleA
{
public string name { get; set; }
public string type { get; set; }
}
Then doing something like this:
string json = File.ReadAllText("a.json");
PersonA personA = JsonConvert.DeserializeObject<PersonA>(json);
PersonB personB = new PersonB() { Email = personA.Email, CreatedDate = personA.CreatedDate };
foreach(var role in personA.Roles)
{
var roleB = role as RoleB;
if (roleB.town != null)
{
personB.RolesB.Add(roleB);
}
else
{
personB.RolesA.Add(new RoleA() { name = roleB.name, type = roleB.type });
}
}