0

I'm using Json.net(Newtonsoft.Json) to serialize or deserialize some class.

There is my class

[DataContract]
Public class Person
{
   [DataMember]
   public string ID { get; set; }
}

public class Student : Person
{
   public string StudentName { get; set;}
}

Now I want to serialize student, But Looks like Json.net only serialize or deserialize DataContract class and DataMember property. It always ignore my StudentName property, But I need it include in.

Is there any way to fixed this? thank you.

qakmak
  • 1,287
  • 9
  • 31
  • 62
  • Have you tried newtonsoft.json? – willaien Sep 06 '15 at 15:09
  • @willaien What? I'm currently using Newtonsoft.Json, and I thought It's the Json.net ..... – qakmak Sep 06 '15 at 15:18
  • Alright. Here's what's likely happening. By default, newtonsoft.json will serialize all properties, but due to your class inheriting attributes from its parent, you have told newtonsoft.json to not serialize those properties without attributes. If you remove all of the attributes, it should work. – willaien Sep 06 '15 at 15:20
  • 4
    This looks like what you need: http://stackoverflow.com/questions/11055225/configure-json-net-to-ignore-datacontract-datamember-attributes – Todd Sep 06 '15 at 15:22
  • @Todd , That's a really good way, It will be more better If you write it as a answer. Also It that will be a low performance problem? – qakmak Sep 06 '15 at 15:54
  • @willaien do you know when such rules came into Newtonsoft.Json serializer? We updated in from 3.5 to latest 13 and now we have absolutely the same trouble such as in this topic. Now I'm wondering is it possible to change with some setting, because I'm not sure we need all the fields in JSON to include Todd's decision – G. Goncharov Aug 11 '23 at 10:29

2 Answers2

0

According to official site you just have to add [DataMember] attribute to StudentName to have this property in the json string.

myroman
  • 532
  • 5
  • 11
  • Is there any other way? Because I don't want add it in my all classes. there is so many classes..... – qakmak Sep 06 '15 at 15:21
0

If you need to include the StudentName property just add [DataMember] attribute to this property.

However, another easier way can be to completely remove [DataContract] and [DataMember] as Newtonsfot.Json doesn't really need them to determine which properties to include.

public class Person
{
    public string ID { get; set; }
}

public class Student : Person
{
   public string StudentName { get; set;}
}

// ...

Student student = new Student() { ID = "1", StudentName = "John" };
string resultJson = Newtonsoft.Json.JsonConvert.SerializeObject(student);
Viktor Bahtev
  • 4,858
  • 2
  • 31
  • 40