0

I need to create different JSON in C#. Sometimes I need to create a Json with specific attributes of a class, and sometimes I need to create a JSON with all the attributes of the class But I don’t know how to delete some attributes(if the attribute is null or empty, I don’t need to create it in the Json, but it the attribute has a value I need it) Example

Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };

string json = JsonConvert.SerializeObject(product);

With that example I create a JSOn with all the attributes , but how can I create A JSON without Price for example? Or if the attribute is a List I need to check if some object is null, don’t create the JSON with the objet in null

Thank you so much

  • 2
    https://stackoverflow.com/questions/6507889/how-to-ignore-a-property-in-class-if-null-using-json-net – Artur Jul 13 '19 at 16:09
  • Possible duplicate of [Newtonsoft ignore attributes?](https://stackoverflow.com/questions/6309725/newtonsoft-ignore-attributes) – Ňɏssa Pøngjǣrdenlarp Jul 13 '19 at 16:12
  • Thanks I am going to check – Siren1234 Jul 13 '19 at 16:14
  • 3
    Possible duplicate of [How to ignore a property in class if null, using json.net](https://stackoverflow.com/questions/6507889/how-to-ignore-a-property-in-class-if-null-using-json-net) – Tobias Tengler Jul 13 '19 at 16:31
  • [How to Ignoring Fields and Properties Conditionally During Serialization Using JSON.Net?](https://stackoverflow.com/q/34304738) may also be what you want, but the question is general enough that it's not clear exactly what you want. – dbc Jul 14 '19 at 02:24

0 Answers0