Convert an object (i.e. any object, such as a person, employee) to byte [] in silverlight

I have a person object and you need to save it as byte [] and get this byte [] again and convert to person object and BinaryFormatter is not available in silverlight

+5
source share
5 answers

Since the namespaces mentioned by t0mm13b are not part of the Silverlight.NET mechanism, the correct way is to use this workaround using a data serializer:

http://forums.silverlight.net/forums/t/23161.aspx

From the link:

string SerializeWithDCS(object obj)
{
    if (obj == null) throw new ArgumentNullException("obj");
    DataContractSerializer dcs = new DataContractSerializer(obj.GetType());
    MemoryStream ms = new MemoryStream();
    dcs.WriteObject(ms, obj);
    return Encoding.UTF8.GetString(ms.GetBuffer(), 0, (int)ms.Position);
}
+6
source

, , protobuf Google.

http://code.google.com/p/protobuf-net/

. .

enter image description here

WCF ↔ Silverlight .

+4

XML Serializer , [] Silverlight.

object address = new Address();

            System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(Address));
            StringBuilder stringBuilder = new StringBuilder();
            using (StringWriter writer = new StringWriter(stringBuilder))
            {
                serializer.Serialize(writer, address);
            }

            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
            byte[] data = encoding.GetBytes(stringBuilder.ToString());
+2

0

MemoryStream

using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;

....
byte[] bPersonInfo = null;
using (MemoryStream mStream = new MemoryStream())
{
     System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new BinaryFormatter ();
     bf.Serialize (mStream, personInfo);
     bPersonInfo = mStream.ToArray ();
}
....
// Do what you have to do with bPersonInfo which is a byte Array ...

// To Convert it back
PersonInfo pInfo = null;
using (MemoryStream mStream = new MemoryStream (bPersonInfo)) {
     System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new BinaryFormatter ();
     pInfo = (PersonInfo) bf.DeSerialize (mStream);
}
// Now pInfo is a PersonInfo object.

Hope this helps, Regards, Tom.

-1
source

All Articles