For .NET. I've tried a lot of different things, but nothing seems to work. Requirements:
- The T of ObservableCollection<T> is an ISerializable
- The ObservableCollection-derived-class ideally is also an ISerializable
- For this context, being an ISerializable = uses only ISerializable technique for serialization, not reflected properties
Environment is Xamarin for Android, I'd prefer to use either JSON.NET or DataContractJsonSerializer. Example uses Newtonsoft 9.0.1
With code like this:
[Serializable]
[KnownType(typeof(ObservableCollectionSerializable.Item))]
public class ObservableCollectionSerializable :
ObservableCollection<ObservableCollectionSerializable.Item>
{
[Serializable]
public class Item : ISerializable
{
readonly string value;
public Item(string value) { this.value = value; }
public Item(SerializationInfo info, StreamingContext context)
{
value = info.GetString("value");
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("value", value);
}
}
}
Invoked like this:
var _item = new Test.ObservableCollectionSerializable.Item("test1");
var c = new Test.ObservableCollectionSerializable();
c.Add(_item);
var serializer = new Newtonsoft.Json.JsonSerializer();
serializer.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver()
{
//IgnoreSerializableInterface = false // not available
};
var stringWriter = new StringWriter();
serializer.Serialize(stringWriter, c);
var json = stringWriter.ToString();
var stringReader = new StringReader(json);
var c2 = (Test.ObservableCollectionSerializable)
serializer.Deserialize(stringReader, typeof(Test.ObservableCollectionSerializable));
var item = c2[0];
Results are:
- "json" variable always ends up "[{}]" - empty
- ISerialize-based methods are never called
- serializer.Deserialize call always throws exception "Newtonsoft.Json.JsonSerializationException: Unable to find a constructor to use for type Notos.App.UI.Android.Test.ObservableCollectionSerializable+Item. A class should either have a default constructor, one constructor with arguments or a constructor marked with the JsonConstructor attribute. Path '[0]', line 1, position 3"