• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1554
  • Last Modified:

Serilize and Deserilize Object to String?

Hello,

I need to serialize objects (strings, numbers, array, arralist, ........) to sting and send it over network to another app that will de-serialize it back to object and use the data?

I found an example online, but is it OK? another thing, I can not figure out the de-serialize part !!!

any help?

Thanks allot
//===========================================================
        public string SerilizeObject(Object obj)
        {
            if (obj == null)
                return null;
            MemoryStream memoryStream = new MemoryStream();
            BinaryFormatter binaryFormatter = new BinaryFormatter();
            binaryFormatter.Serialize(memoryStream, obj);
            string str = System.Convert.ToBase64String(memoryStream.ToArray());
            return str;
        }
        // Convert a byte array to an Object
        //===========================================================
        public Object DeSerilizeObject(string str)
        {

            if(str == null)
                return null;
???
???
???

            return obj;
        }
        //===========================================================

Open in new window

0
Data-Base
Asked:
Data-Base
  • 12
  • 10
  • 3
  • +2
2 Solutions
 
MonstahCommented:
With no need to convert it to string on the serialize method, you just output the bytearray. Hope this helps.
        public Object DeSerilizeObject(byte[] OneByteArray)
        {
            MemoryStream ms = new MemoryStream(OneByteArray);
            BinaryFormatter bf = new BinaryFormatter();
            ms.Position = 0;

            return bf.Deserialize(ms);
        }

Open in new window

0
 
Gene_CypCommented:
Here's the key part you are missing:
Stream to string:

byte[] b = MyMemoryStream.ToArray();
string s = System.Text.Encoding.UTF8.GetString(b);

String to stream:

string s = "whatever";
byte[] b = System.Text.Encoding.UTF8.GetBytes(s);
MemoryStream ms = new MemoryStream(b);
 
0
 
lazyberezovskyCommented:

public static string SerilizeObject(Object obj)
{
    if (obj == null) return null;

    MemoryStream memoryStream = new MemoryStream();
    BinaryFormatter formatter = new BinaryFormatter();
    formatter.Serialize(memoryStream, obj);
    return Encoding.ASCII.GetString(memoryStream.ToArray());            
}

public static Object DeSerilizeObject(string str)
{
    if(str == null) return null;
    
    MemoryStream memoryStream = new MemoryStream(Encoding.ASCII.GetBytes(str));
    BinaryFormatter formatter = new BinaryFormatter();
    return formatter.Deserialize(memoryStream);
}

Open in new window

0
Cloud Class® Course: Amazon Web Services - Basic

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

 
Data-BaseAuthor Commented:
thanks,

the reason whey I want it to be string it's just to easily wok with it (for example save it to file) as well as send it over network

now I have the client server code but the server filed to send the Byte[] array !!! while it sends strings with no problems !!!

so in that case how to serialize an object and send it with the code (with server)?
and how I can get it back at the client?

asked that before, but I did not get a real answer

public void RunServer(string SrvIP,int SrvPort)
        {
            try
            {
                var ipAd = IPAddress.Parse(SrvIP);


                /* Initializes the Listener */
                if (ipAd != null)
                {
                    var myList = new TcpListener(ipAd, SrvPort);

                    /* Start Listeneting at the specified port */
                    myList.Start();

                    Console.WriteLine("The server is running at port "+SrvPort+"...");
                    Console.WriteLine("The local End point is  :" + myList.LocalEndpoint);
                    Console.WriteLine("Waiting for a connection.....");


                    while (true)
                    {
                        Socket s = myList.AcceptSocket();
                        Console.WriteLine("Connection accepted from " + s.RemoteEndPoint);

                        var b = new byte[100];
                        int k = s.Receive(b);
                        Console.WriteLine("Recieved...");
                        for (int i = 0; i < k; i++)
                            Console.Write(Convert.ToChar(b[i]));
                        string cmd = Encoding.ASCII.GetString(b);
                        if (cmd.Contains("CLOSE-CONNECTION"))
                            break;
                        var asen = new ASCIIEncoding();
                        
                        // sending text 
                        s.Send(asen.GetBytes("The string was recieved by the server."));

                        Console.WriteLine("\nSent Acknowledgement");
                        s.Close();
                        Console.ReadLine();
                    }
                    /* clean up */

                    myList.Stop();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Error..... " + e.StackTrace);
            }
        }
//============================================================
public object runClient(string SrvIP, int SrvPort)
        {
            try
            {
                var tcpclnt = new TcpClient();
                Console.WriteLine("Connecting.....");

                tcpclnt.Connect(SrvIP, SrvPort);
                // use the ipaddress as in the server program


                Console.WriteLine("Connected");
                Console.Write("Enter the string to be transmitted : ");

                var str = Console.ReadLine();
                Stream stm = tcpclnt.GetStream();

                var asen = new ASCIIEncoding();
                if (str != null)
                {
                    var ba = asen.GetBytes(str);
                    Console.WriteLine("Transmitting.....");

                    stm.Write(ba, 0, ba.Length);
                }

                var bb = new byte[2000];

                var k = stm.Read(bb, 0, bb.Length);


                for (var i = 0; i < k; i++)
                    Console.Write(Convert.ToChar(bb[i]));

                Console.ReadLine();
                
                tcpclnt.Close();
            }

            catch (Exception e)
            {
                Console.WriteLine("Error..... " + e.StackTrace);
            }

        }

Open in new window

0
 
Data-BaseAuthor Commented:
hello,

thank you all for the answer

@azyberezovsky

I tested the code and it work but when I tested serialize / de-serialize a string (an object)  with Norwegian letters (åøæ) it come back (???)

how I can fix that?
using System;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string input = Console.ReadLine();
            Console.WriteLine(DeSerilizeObject(SerilizeObject("Hello")));
            Console.WriteLine(DeSerilizeObject(SerilizeObject(input)));
            Console.ReadLine();
        }

        public static string SerilizeObject(Object obj)
        {
            if (obj == null) return null;

            MemoryStream memoryStream = new MemoryStream();
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(memoryStream, obj);
            return Encoding.ASCII.GetString(memoryStream.ToArray());
        }

        public static Object DeSerilizeObject(string str)
        {
            if (str == null) return null;

            MemoryStream memoryStream = new MemoryStream(Encoding.ASCII.GetBytes(str));
            BinaryFormatter formatter = new BinaryFormatter();
            return formatter.Deserialize(memoryStream);
        }
    }
}

Open in new window

0
 
Anurag ThakurTechnical ManagerCommented:
to get the string of xml after serialization you can use the code same provided in this sample
http://geekswithblogs.net/TimH/archive/2006/02/09/68857.aspx

i read your question and you mentioned that you need to serialize arraylists too but i guess microsoft does not support serialization for them
0
 
Data-BaseAuthor Commented:
raqi0017

Thanks for your reply

how to solve the arraylist? and what about other costume objects?
0
 
Anurag ThakurTechnical ManagerCommented:
custom objects can be serialized, its not an issue
instead of array list you can use List<T> objects and the T type should be serializeable
that will solve your problem
0
 
lazyberezovskyCommented:
Data-Base, you can fix Norwegian letters using Encoding.Unicode (or Encoding.UTF8) instead of Encoding.ASCII
0
 
Data-BaseAuthor Commented:
@ lazyberezovsky
I did, it did not work !

I get an error!
0
 
Data-BaseAuthor Commented:
@ragi0017

Thanks allot,
http://geekswithblogs.net/TimH/archive/2006/02/09/68857.aspx sounds very interesting,
0
 
Gene_CypCommented:
Data-base always go for the simple and most eloquent solutions, did u implement that small bit of code I gave to you further above?
0
 
Data-BaseAuthor Commented:
@Gene_Cyp

thank you, I did not fully understand your solution !!
does it mean I can input any object as a stream?

I mean I need to serialize the data, (object) so I'm not sure how to use your solution, sorry for my dump question, I need to read more, i'm very new to this

cheers
0
 
Data-BaseAuthor Commented:
@ lazyberezovsky
I did, it did not work !

I get error

No map for object '100663296'.    at    return formatter.Deserialize(memoryStream);
0
 
Gene_CypCommented:
In your serialise, you had
string str = System.Convert.ToBase64String(memoryStream.ToArray());
change that to :
 byte[] b = MyMemoryStream.ToArray();
string s = System.Text.Encoding.UTF8.GetString(b);

 And make your deserialize as follows:
 
public Object DeSerializeObject(string str)
        {
 
            if(str == null)
                return null;

byte[] b = System.Text.Encoding.UTF8.GetBytes( str);
MemoryStream ms = new MemoryStream(b);

BinaryFormatter bf = new BinaryFormatter();
 ms.Position = 0;
 
            return bf.Deserialize(ms);

        }
 
0
 
Data-BaseAuthor Commented:
@Gene_Cyp

Thanks allot, now I have tested it but I get the error "No map for object '100663296'." on

return bf.Deserialize(ms);
0
 
Gene_CypCommented:
Add the following just before the return line:
ms.Seek(0, SeekOrigin.Begin );
 
Let me know if it's fixed the problem

 
0
 
Gene_CypCommented:
Also, does the object that you send have sub-objects of its own?
0
 
Gene_CypCommented:
Also, break the return into mroe lines so that it can be debugged properly.
 
make a temp object, such as:
Object myObj = null;
try
{
myObj = bf.Deserialize(ms);
}
catch(Exception ex)
{
//
}
return myObj;
 
The add a break point at the curly bracket right below the word "try", and follow the execution threw, when it throws the exception, look atthe INNER exception and post the output here please.
0
 
Gene_CypCommented:
I'm making these into separate posts so apologies to ppl getting -email alerts ;)
If you are sending from one Computer and receiving from another, you need to make sure that the.NET Framework versions are exactly the same.
0
 
Data-BaseAuthor Commented:
@Gene_Cyp

Thank you

>>Add the following just before the return line:
>>ms.Seek(0, SeekOrigin.Begin );

I did and I get the same error!


right now I'm doing it on the same Computer

my idea is to get a variable (object type string,number, array,hashtable or any other variable/object types) and convert it to something easy to send to another computer and convert it back!

is it the right approach?
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace ConsoleApplication3
{
    internal class Program
    {
        private static void Main()
        {
            string input = Console.ReadLine();
            //Console.WriteLine(DeSerilizeObject(SerilizeObject("Hello")));
            Console.WriteLine(DeSerilizeObject(SerilizeObject(input)));
            Console.ReadLine();
        }

        //===========================================================
        public static string SerilizeObject(Object obj)
        {
            if (obj == null)
                return null;
            MemoryStream memoryStream = new MemoryStream();
            BinaryFormatter binaryFormatter = new BinaryFormatter();
            binaryFormatter.Serialize(memoryStream, obj);
            byte[] b = memoryStream.ToArray();
            string str = System.Text.Encoding.UTF8.GetString(b);
            return str;
        }
        // Convert a byte array to an Object
        //===========================================================
        public static Object DeSerilizeObject(string str)
        {

            if (str == null)
                return null;

            byte[] b = Encoding.UTF8.GetBytes(str);
            MemoryStream ms = new MemoryStream(b);
            BinaryFormatter bf = new BinaryFormatter();

            ms.Position = 0;

            Console.WriteLine(bf.GetType().ToString());
            Console.WriteLine(ms.GetType().ToString());
            Console.ReadLine();

            ms.Position = 0;
            ms.Seek(0, SeekOrigin.Begin);
            return bf.Deserialize(ms);

        } 
        //===========================================================

    }
}

Open in new window

0
 
Gene_CypCommented:
Add that try catch as follows (see code snippet) and add a breakpoint in your debugger, at the curly bracket where the try is, then using f10, go through each code line, line by line, until it throws the exception, check the value of the "error" string inside the catch once u go through it and post it here please.
public static Object DeSerilizeObject(string str) 
        { 
 
            if (str == null) 
                return null; 
 
            byte[] b = Encoding.UTF8.GetBytes(str); 
            MemoryStream ms = new MemoryStream(b); 
            BinaryFormatter bf = new BinaryFormatter(); 
 
            ms.Position = 0; 
 
            Console.WriteLine(bf.GetType().ToString()); 
            Console.WriteLine(ms.GetType().ToString()); 
            Console.ReadLine(); 
 
            ms.Position = 0; 
            ms.Seek(0, SeekOrigin.Begin); 
            Object myObj = null;

try
{
myObj = bf.Deserialize(ms);
}
catch(Exception ex)
{
string error = "Message: " + ex.Message + "\n\nInner Exception: " + ex.InnerException + "\n\nSource: " + ex.Source + "\n\nStackTrace: " + ex.StackTrace;
}
return myObj;

 
        }

Open in new window

0
 
Data-BaseAuthor Commented:
thanks again

it does not return any thing
no value and no error !!!

just a new line
0
 
Gene_CypCommented:
You ened to pick this up in the debugger, anyway I'll make it easier:
Underneath that string error = ....
Add:
Console.WriteLine(error);
0
 
Data-BaseAuthor Commented:
oh sorry, yes I forgot to put the rro from the debuger :-)

here is the out put:

helloworld
Message: No map for object '100663296'.

Inner Exception:

Source: mscorlib

StackTrace:    at System.Runtime.Serialization.Formatters.Binary.__BinaryParser.
ReadObject()
   at System.Runtime.Serialization.Formatters.Binary.__BinaryParser.Run()
   at System.Runtime.Serialization.Formatters.Binary.ObjectReader.Deserialize(He
aderHandler handler, __BinaryParser serParser, Boolean fCheck, Boolean isCrossAp
pDomain, IMethodCallMessage methodCallMessage)
   at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize
(Stream serializationStream, HeaderHandler handler, Boolean fCheck, Boolean isCr
ossAppDomain, IMethodCallMessage methodCallMessage)
   at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize
(Stream serializationStream)
   at ConsoleApplication3.Program.DeSerilizeObject(String str) in C:\Users\Sarma
d\My Dropbox\Work\Visual Studio 2010\Projects\ConsoleApplication3\ConsoleApplica
tion3\Program.cs:line 48

line 48 is myObj = bf.Deserialize(ms);
0
 
Gene_CypCommented:
I'll endeavour to help him resolve his problem. Have been quite busy these last few days.
 
 
0
 
lazyberezovskyCommented:
Try following code:


public static string SerilizeObject(Object obj)
{
    if (obj == null) return null;

    MemoryStream memoryStream = new MemoryStream();
    BinaryFormatter formatter = new BinaryFormatter();
    formatter.Serialize(memoryStream, obj);
    return Convert.ToBase64String(memoryStream.ToArray());
}

public static Object DeSerilizeObject(string str)
{
    if (str == null) return null;

    MemoryStream memoryStream = new MemoryStream(Convert.FromBase64String(str));
    memoryStream.Position = 0;
    BinaryFormatter formatter = new BinaryFormatter();
    return formatter.Deserialize(memoryStream);
}

Open in new window

0
 
Data-BaseAuthor Commented:
Thanks that worked perfectly :-)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 12
  • 10
  • 3
  • +2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now