I have a class that looks like
public class DemoUsersList : List<DemoUser> {
public DemoUser AdminUser;
}public class DemoUser {
public int Id { get; set; }
public string Name { get; set; }
}
Now, I have to serialize this collection. Now, serializer got a problem! what to serialize, base class or derived class? You would end-up getting only the base class
var users = new DemoUsersList();
users.Add( new DemoUser { Id = 1, Name = "guru" });
users.Add(new DemoUser { Id = 2, Name = "aaa" });
users.AdminUser= new DemoUser{Id=0, Name="Admin"} ;
var str = JsonConvert.SerializeObject(users);
Console.WriteLine(str);
Workaround? Just allow serializing derived class and expose the base class as a member in the serial class. Following code can do this for you.
[JsonObject(MemberSerialization=MemberSerialization.OptIn)]
public class DemoUsersList : List<DemoUser> {
[JsonProperty]
public IEnumerable<DemoUser> Users {
get { return this.Select(x => x); }
}
[JsonProperty]
public DemoUser AdminUser;
No comments:
Post a Comment