Json Deserialised don't override the default values in the property

 public class Student
 {
      public string Name { get; set;} = "ABCD";
      public List<Subject> Subjects {get; set;}
      public Student()
      {
            Subjects = new List<Subject>();
            SetDefaultSubject();
       }

      private void SetDefaultSubject()
      {
            this.Subjects.Add(new Subject(){Name = "English"});
            this.Subjects.Add(new Subject(){Name = "Maths"});
      }
}

public class Subject
{
     public string Name {get; set;}
}

I have a Json String which look like this

var jsonStudentData = @"{""Name"":""ABC"",""Subjects"":[{""Name"":""English""},{""Name"":""Maths""},{""Name"":""Hindi""},{""Name"":""Social Studies""}]}";

This is my code where i am deserialising jsonStudentData

JsonConvert.DeserializeObject<Student>(jsonStudentData);

I am getting the Output
Name = ABC, Subject [English,Maths,English,Maths,Hindi,Social Studies]

but i want Output

Name = ABC, Subject [English,Maths,Hindi,Social Studies]

Am i Doing Wrong anything here.

Jon Skeet
people
quotationmark

Well, your expectations are incorrect. Basically, the JSON deserializer is - entirely reasonably, IMO - executing code equivalent to:

var student = new Student
{
    Name = "ABC",
    Subjects =
    {
        // Each line here will just call Add
        new Subject { Name = "English" },
        new Subject { Name = "Maths" },
        new Subject { Name = "Hindi" },
        new Subject { Name = "Social Studies" },
    }
};

That's what your JSON basically says it should do. It's your SetDefaultSubjects which is adding more information, regardless of what the JSON says.

I would personally suggest you remove the call to SetDefaultSubjects from your constructor - perhaps add a factory method of CreateStudentWithDefaultSubjects.

You might also consider making your List a set of some kind (e.g. HashSet) and make Subject implement IEquatable<Subject>, so that you can add duplicates and they'll be ignored.

people

See more on this question at Stackoverflow