Optionally serialize a property based on its runtime value

后端 未结 2 1666
庸人自扰
庸人自扰 2021-02-04 05:27

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

2条回答
  •  执笔经年
    2021-02-04 05:40

    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);
        }
    }
    

提交回复
热议问题