-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.

0

1 Answer 1

3

Just use the JsonIgnore attribute.

public class Person : Description
{
    [JsonIgnore]
    public int Id { get; set; }
}
Sign up to request clarification or add additional context in comments.

1 Comment

This works for me. Thank you.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.