Serializing an 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 newin a property, serialization will fail. There is no exception; Personsjust not serialized.

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

Why is this?

(This example does not make much sense, I know, this is just an example. The goal later is to change the data type of the property public new ICollection<PersonDto> Persons { get; set; })

+3
source share
2 answers

I found an easier way to solve this problem without creating a custom JsonConverter

If you put the attribute JsonPropertyon top of the property, it will work.

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

, Json.Net . , JsonIgnore. - , .

+2

, , Person JSON, , JsonConverter. :

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);
    }
}

:

JsonConvert.SerializeObject(yourObject, new PersonConverter())
+1

All Articles