0

I have a class of which I serialize objects to JSON using json.net. The class has some property that I usually didn't want serialized, so I marked it with JsonIgnore.

public class SomeClass
{
    [JsonIgnore]
    public int ID { get; set; }
    public int SecondID { get; set; }
    public string Name { get; set; }
}

Now, in a different context, I wish to export objects of the same class, but here I wish to also export the ID (that I have flagged to be ignored in the first context).

Is it possible to dynamically flag a property to be ignored before serializing to JSON or do I have to write a custom serializer to achieve this?

How can I achieve the desired behavior in the simplest possible way?

Mr. Blonde
  • 711
  • 2
  • 12
  • 27

1 Answers1

0

Here you can make a list of properties you want to ignore :

[JsonIgnore]
    public List<Something> Somethings { get; set; }

 //Ignore by default
    public List<Something> Somethings { get; set; }

JsonConvert.SerializeObject(myObject, 
                            Newtonsoft.Json.Formatting.None, 
                            new JsonSerializerSettings { 
                                NullValueHandling = NullValueHandling.Ignore
                            });
Sha La
  • 1
  • 3