2

I have two classes that look something like this:

class BaseClass
{
    public string Property1;
}

class ChildClass : BaseClass
{
    public string Property2;
}

If I create an instance of ChildClass, and then cast up to the BaseClass and Json Serialize it, the attributes of the ChildClass show up.

ChildClass childInstance = new ChildClass() { Property1 = "1", Property2 = "2" };

BaseClass baseInstance = (BaseClass)childInstance;

Console.WriteLine(JsonConvert.SerializeObject(baseInstance, Formatting.Indented));
            
{
  "Property2": "2",
  "Property1": "1"
}

This is despite the fact that, of course, Property2 cannot be accessed from baseInstance in code.

Why is this happening and is there a nice fix?

ajax2112
  • 228
  • 1
  • 6
  • You'll probably need your own [`ContractResolver`](https://www.newtonsoft.com/json/help/html/contractresolver.htm). [This answer](https://stackoverflow.com/a/35634915/3181933) aims to do the opposite. – ProgrammingLlama Sep 14 '21 at 07:07
  • The serializer serialize actual object and not the concrete casted view. Pay attention, the SerializeObject method gets object parameter. In your case you cast it to BaseClass, but the serializer see it as object. But it is still same object (ChildClass) – Alexey Nis Sep 14 '21 at 07:17
  • Minor nit: those aren't "attributes" - they are fields (although arguably they should be properties). Attributes has a specific meaning in .NET, and it isn't this. – Marc Gravell Sep 14 '21 at 07:19

1 Answers1

2

SerializeObject is a non-generic method that takes object as the parameter - it then uses .GetType() internally to discover what the object is. As such: what type you are thinking of in your code doesn't matter; all that matters is what the object actually is. From the perspective of an object parameter: none of the relevant members are directly visible. That isn't a barrier at all.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900