samus
samus

Reputation: 6202

JSON.NET serialization issue with protected property setter

I have a base class, BaseRecord, with an int property, RecordTypeId, that holds an enum value for the a record's type.

public class BaseRecord
{
    public int RecordTypeId { get; set; }
}

If set is made protected

    public int RecordTypeId { get; protected set; }

then RecordTypeId becomes 0 after construction, regardless of the value passed in?

public class ChildRecord : BaseRecord
{
    public int RecordId { get; set; }

    public ChildRecord( int recordTypeId, int recordId )
    {
        RecordTypeId = recordTypeId;
        RecordId = recordId;
    }
}

Since RecordTypeId is only set in a constructor, and is only used by a data access layer, I figured to make it protected.

Upvotes: 0

Views: 1344

Answers (1)

Flater
Flater

Reputation: 13773

In the comments you mentioned that this happens after deserialization.

You did not specify which serializer you're using; but every serializer I know of always works based on a parameterless constructor and publically settable properties.
The serializer creates an object (var newObj = new T(); where T is generic) and then, for each property in the serialized data, tries to set the property on newObj.

Since the serializer does not inherit from BaseRecord, it has no access to the protected properties of the BaseRecord.

From the comments below
Think of the serializer as a separate class. It can access a BaseRecord's public properties, and set their value (if the setter is public). But if the setter is protected, then an external class (the serializer) is unable to set the value. What's inside the JSON data doesn't matter, it's about whether the serializer (an external class) is allowed to set the value of the property or not.
You'll see that a class with properties marked as public get; protected set; can be serialized to JSON (because the getter is public) but not deserialized from JSON (because the setter is not public).


Since RecordTypeId is only set in a constructor, and is only used by a data access layer, I figured to make it protected.

Is it possible that you are confusing protected with internal?

Protected is only accessible by those who inherit. Internal is accessble by everyone in the same assembly (project). Your description here seems to suggest that you're trying to do the latter.

From the comments below:
Keep in mind that JSON.NET is in an assembly of its own, so even internal access won't work since this is going across assembly borders.

Upvotes: 2

Related Questions