0

A bit similar question but the answer does not make sense here

public static void Main(string[] args)
{
   var myObject = new ChildClass()
   {
     P1 = "p1",
     P2 = "P2",
   };
   var data = (ParentClass)myObject;
   var jsonData = Newtonsoft.Json.JsonConvert.SerializeObject(data);

   Console.WriteLine(jsonData);
}

class ParentClass
{
  public string P1 { get; set; }
}

class ChildClass : ParentClass
{
  public string P3 { get; set; }
}  

would return

{"P2":"P2","P1":"p1"}

using JsonIgnore on the base or child class does not make sense, since I like the process work as normal for all other normal cases.

dbc
  • 104,963
  • 20
  • 228
  • 340
  • Json.NET serializes the actual properties of the object passed in, not the declared properties of the reference. To serialize/deserialize as a base class object you need to use a custom contract resolver. See e.g. [How to exclude properties from JsonConvert.PopulateObject that don't exist in some base type or interface?](https://stackoverflow.com/q/56467203/3744182) or [Using JSON.net, how do I prevent serializing properties of a derived class, when used in a base class context?](https://stackoverflow.com/q/5872855/3744182). – dbc Nov 14 '21 at 04:19
  • 1
    Do those questions answer yours sufficiently? Or do you need more specific help? – dbc Nov 14 '21 at 04:19
  • works but not very intuitive, I might use a clone as oppose to cast! – Sadjad Bahmanpour Nov 14 '21 at 04:32

1 Answers1

0

If you want to serialize a parent class with the default serializer, you'll need to make a parent class:

var myObject = new ParentClass()
{
  P1 = "p1"
};

You can't just turn off polymorphism/ignore that the object is-a child by casting it to a parent.. If the root of the issue outside the contrived example is that your device X is delivering you a Child and you want a Parent, perhaps look to see if a mapper can map your child to a parent for you (or take out the boring boilerplate of only copying over those properties present on a parent)..

Caius Jard
  • 72,509
  • 5
  • 49
  • 80