-1

How to JsonConvert.SerializeObject after object cast?

I have two classes like this example, and I want my serialized json to not include the "Id" field.

public class Person : Description
{
    public int Id { get; set; }
}
public class Description
{
    public string Name { get; set; }
}


Person person = new Person() { Id = 1, Name = "Bill" };
Description description = person;
string jsonDescription = JsonConvert.SerializeObject(description);
Console.WriteLine(jsonDescription);
// {"Id":1,"Name":"Bill"}

I've tried several things like casting with "as" or casting with .Cast() but no luck yet.

Thank you for your suggestions.

Erik
  • 122
  • 9

1 Answers1

3

Just use the JsonIgnore attribute.

public class Person : Description
{
    [JsonIgnore]
    public int Id { get; set; }
}
pmcilreavy
  • 3,076
  • 2
  • 28
  • 37