How to Serialize list<objects> using DataContractSerializer
Library shared between server and client contains interface :
[ServiceContract(SessionMode=SessionMode.Required, CallbackContract=typeof(IClient))]
public interface IServer
{
// Node interface methods
[OperationContract(Name = "UploadResults", IsOneWay = true)]
void UploadResults(string result);
}
Server code implementing the interface :
public void UploadResults(string result)
{
try
{
// Get portfolio from stream
DataContractSerializer serializer = new DataContractSerializer(typeof(MyClass));
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(result)))
{
MyClass class = (MyClass)serializer.ReadObject(ms);
.....
}
}
catch (Exception ex)
{
}
}
Client code calling Server:
// Send myclass object to server
try
{
// Write portfolio to stream
DataContractSerializer serializer = new DataContractSerializer(typeof(MyClass));
using (var stream = new MemoryStream())
{
serializer.WriteObject(stream, myclassObj开发者_如何学运维);
// Send result back to server
string result = Encoding.UTF8.GetString(stream.GetBuffer(), 0, (int)stream.Position);
Server.UploadResults(result);
}
}
catch (Exception ex)
{
}
MyClass :
[DataContract]
[KnownType(typeof(AClass))]
[KnownType(typeof(List<AClass>))]
public class MyClass
{
[DataMember]
public List<AClass> History { get; set; }
[DataMember]
public int Count { get; set; }
}
AClass :
[DataContract]
public class AClass
{
[DataMember]
public int x;
[DataMember]
public int y;
}
精彩评论