1
 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.

Sachin
  • 11
  • 5

2 Answers2

1

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
0

Alternatively, you can use C# function to deserialize.

Assembly: System.Web.Extensions (in System.Web.Extensions.dll)

    string jsonStudentData = @"{""Name"":""ABC"",""Subjects"":[{""Name"":""English""},{""Name"":""Maths""},{""Name"":""Hindi""},{""Name"":""Social Studies""}]}";
    JavaScriptSerializer serializer = new JavaScriptSerializer();
    Student  newStudent = serializer.Deserialize<Student>(jsonStudentData);
Prasanth V J
  • 1,126
  • 14
  • 32