对于.NET。我尝试了很多不同的东西,但似乎没有任何效果。要求:
环境是适用于Android的Xamarin,我更喜欢使用JSON.NET或DataContractJsonSerializer。示例使用Newtonsoft 9.0.1
使用这样的代码:
[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);
}
}
}
像这样调用:
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];
结果是: