Fundamentally, I want to include or omit a property from the generated Json based on its value at the time of serialization.
More-specifically, I have a type that knows
Because you are asking to do it based on the value of a property what you can do is put the data into a dictionary. You can exclude adding the value to the dictionary. Below is a simple example of how to get the data out of an object.
public class Class1
{
public string Name { get; set; }
}
[TestFixture]
public class Tests
{
[Test]
public void ConvertTest()
{
var dictionary = new Dictionary();
var @class = new Class1 { Name = "Joe" };
var propertyInfos = typeof (Class1).GetProperties();
foreach (PropertyInfo propertyInfo in propertyInfos)
{
dictionary.Add(propertyInfo.Name, propertyInfo.GetValue(@class, BindingFlags.GetProperty, null, null, null));
}
var serializeObject = JsonConvert.SerializeObject(dictionary);
var o = JsonConvert.SerializeObject(@class);
Console.WriteLine(serializeObject);
Console.WriteLine(o);
var class1 = JsonConvert.DeserializeObject(serializeObject);
Console.WriteLine(class1.Name);
}
}