DataCollection | ComponentOne
Work with DataCollection / Serialization
In This Topic
    Serialization
    In This Topic

    The DataCollection library supports serializing .NET objects to JSON streams and deserializing the JSON streams back to .NET objects. For this purpose, the library provides the C1.DataCollection.Serialization assembly. It provides JsonConverters that assist the JsonSerializer class to serialize and deserialize classes that by default cannot be serialized or deserialized.

    The serialization feature is useful while performing remote binding in web-applications with Blazor platform, where the filter and sort are performed in the server. For this purpose, C1.DataCollection.Serialization provides three types of JsonConverters, FilterExpressionJsonConverter, SortDescriptionJsonConverter and NotifyCollectionChangedEventArgsJsonConverter class.

    The FilterExpressionJsonConverter class helps in serializing and deserializing the FilterExpression class, which provides abstract filter expressions for data collections. The FilterExpression class cannot be serialized or deserialized automatically as it has a polymorphic structure.

    var options = new JsonSerializerOptions { Converters = { new C1.DataCollection.Serialization.FilterExpressionJsonConverter() } };
    var filterString = JsonSerializer.Serialize(filterExpression, options);
    
    var options = new JsonSerializerOptions { Converters = { new C1.DataCollection.Serialization.FilterExpressionJsonConverter() } };
    var filterExpression = JsonSerializer.Deserialize<FilterExpression>(filter, options);
    

    The SortDescriptionJsonConverter class helps in serializing and deserializing the SortDescription class, which describes a sort operation for data collection. The SortDescription class does not contain any default constructors. Moreover, the properties are read-only, and hence cannot be serialized or deserialized.

    var options = new JsonSerializerOptions { Converters = { new C1.DataCollection.Serialization.SortDescriptionJsonConverter() } };
    var sortDescriptions = JsonSerializer.Deserialize<SortDescription[]>(sort, options);
    

    The NotifyCollectionChangedEventArgsJsonConverter class helps in serializing and deserializing the NotifyCollectionChangedEventArgs class, which contains the properties NewItems and OldItems of type IList that do not specify the type of the items. This makes it impossible for the JsonSerializer to deserialize the items of the list. The C1.DataCollection.Serialization assembly provides the inherited NotifyCollectionChangedEventArgs<T> class. Hence, while deserializing, the type is passed to the NotifyCollectionChangedEventArgsJsonConverter and the items are deserialized correctly.

    var options = new JsonSerializerOptions { Converters = { new NotifyCollectionChangedEventArgsJsonConverter() } };
    var notify = JsonSerializer.Deserialize<NotifyCollectionChangedEventArgs<T>>(filter, options);