FatAlbert
FatAlbert

Reputation: 4970

Serialize inherited property declared new with Json.Net doesn't work

Json.Net has no problem serializing an overridden property in a child class.

public override ICollection<Person> Persons { get; set; }

But if I try to use new on the property, the serialization fails. There's no exception; Persons are just never serialized.

public new ICollection<Person> Persons { get; set; }

Why is this?

(This example doesn't make much sense, I know. It's only an example. The goal later is to be able to change datatype of the property public new ICollection<PersonDto> Persons { get; set; })

Upvotes: 3

Views: 2213

Answers (2)

FatAlbert
FatAlbert

Reputation: 4970

I discovered a simpler way to solved this without having to create a custom JsonConverter

If you put the attribute JsonProperty over the property it works.

[JsonProperty]
public new ICollection<PersonDto> Persons { get; set; }

I don't know why Json.Net needs the attribute here. Normally it serializes everything that isn't decorated with JsonIgnore. If someone knows, you're welcome to drop a comment.

Upvotes: 2

svick
svick

Reputation: 244757

If you want to do this because you want to specify how exactly will be Person serialized to JSON, I think a better solution would be to use a custom JsonConverter. The converter could look something like this:

class PersonConverter : JsonConverter
{
    public override void WriteJson(
        JsonWriter writer, object value, JsonSerializer serializer)
    {
        var person = (Person)value;
        serializer.Serialize(
            writer,
            new
            {
                Name = person.LastName,
                Age = (int)(DateTime.Now - person.BirthDate).TotalDays / 365
            });
    }

    public override object ReadJson(
        JsonReader reader, Type objectType, object existingValue,
        JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }

    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(Person);
    }
}

You could then use it like this:

JsonConvert.SerializeObject(yourObject, new PersonConverter())

Upvotes: 1

Related Questions