A serializing object that inherits from List <T>
When I try to serialize this collection, the name property is not serialized.
public class BCollection<T> : List<T> where T : B_Button { public string Name { get; set; } } BCollection<BB_Button> bc = new BCollection<B_Button>(); bc.Name = "Name";// Not Serialized! bc.Add(new BB_Button { ID = "id1", Text = "sometext" }); JavaScriptSerializer serializer = new JavaScriptSerializer(); string json = serializer.Serialize(bc); Only if I create a new class (without List<t> inheritance) and define the string Name property and List<B_Button> bc = new List<B_Button>(); property List<B_Button> bc = new List<B_Button>(); I get the correct result.
+4
1 answer
In many serializers (and actually data binding), an object or object or an (exclusive) list; the presence of properties in the list is usually not supported. I would reorganize the encapsulation of the list:
public class Foo<T> { public string Name {get;set;} private readonly List<T> items = new List<T>(); public List<T> Items { get { return items; } } } Also; How do you plan to present this in JSON? The IIRC JSON array syntax also prevents you from adding additional properties.
+6