473,624 Members | 2,566 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

serialize/deserialize object into string

Val
How can I serialize/deserialize an object into a string. Existing examples
seem to be showing this operation for files only.

Thansk
Jul 17 '06 #1
6 45682
What you are really asking is how to convert a stream (e.g. MemoryStream) to
a string. If you are using the BinaryFormatter the MemoryStream you serialize
to or from can be converted to / from a string as follows:

Stream to string:

byte[] b = MyMemoryStream. ToArray();
string s = System.Text.Enc oding.UTF8.GetS tring(b);

String to stream:

string s = "whatever";
byte[] b = System.Text.Enc oding.UTF8.GetB ytes(s);
MemoryStream ms = new MemoryStream(b) ;

Cheers.
Peter
--
Co-founder, Eggheadcafe.com developer portal:
http://www.eggheadcafe.com
UnBlog:
http://petesbloggerama.blogspot.com


"Val" wrote:
How can I serialize/deserialize an object into a string. Existing examples
seem to be showing this operation for files only.

Thansk
Jul 17 '06 #2
Val <Va*@discussion s.microsoft.com wrote:
How can I serialize/deserialize an object into a string. Existing examples
seem to be showing this operation for files only.
using System.IO;
using System.Runtime. Serialization;
using System.Runtime. Serialization.F ormatters.Binar y;

....

MemoryStream memoryStream = new MemoryStream();
BinaryFormatter binaryFormatter = new BinaryFormatter ();
binaryFormatter .Serialize(memo ryStream, targetObject);
string str = System.Convert. ToBase64String( memoryStream.To Array());

where targetObject is the object that you are trying to serialize.
--
Thomas T. Veldhouse
Key Fingerprint: 2DB9 813F F510 82C2 E1AE 34D0 D69D 1EDC D5EC AED1

Jul 17 '06 #3
Hey

Just try with this code.. it seriliaze an object to a string..

using System;
using System.IO;
using System.Runtime. Serialization;
using System.Runtime. Serialization.F ormatters.Binar y;

namespace SeriliazationEx
{
[Serializable()] //Set this attribute to all the classes that want to
serialize
public class Employee
{
public int EmpId;
public string EmpName;

//Default constructor
public Employee()
{
EmpId = 0;
EmpName = null;
}
}

public class ObjSerial
{
public static void Main(String[] args)
{
//Create a new Employee object
Employee mp = new Employee();
mp.EmpId = 10;
mp.EmpName = "Omkumar";

//Add code below for serialization
string s =
System.Text.Enc oding.UTF8.GetS tring(getByteAr rayWithObject(m p));
Console.WriteLi ne(s);
}
public static byte[] getByteArrayWit hObject(Object o)
{
/*

1) Create a new MemoryStream class with the CanWrite property set to true
(should be by default, using the default constructor).

2) Create a new instance of the BinaryFormatter class.

3) Pass the MemoryStream instance and your object to be serialized to the
Serialize method of the BinaryFormatter class.

4) Call the ToArray method on the MemoryStream class to get a byte array
with the serialized data.

*/

MemoryStream ms = new MemoryStream();
BinaryFormatter bf1 = new BinaryFormatter ();
bf1.Serialize(m s, o);
return ms.ToArray();
}
}
}

Veera.
"Val" wrote:
How can I serialize/deserialize an object into a string. Existing examples
seem to be showing this operation for files only.

Thansk
Jul 17 '06 #4
Peter Bromberg [C# MVP] <pb*******@yaho o.nospammin.com wrote:
What you are really asking is how to convert a stream (e.g. MemoryStream) to
a string. If you are using the BinaryFormatter the MemoryStream you serialize
to or from can be converted to / from a string as follows:

Stream to string:

byte[] b = MyMemoryStream. ToArray();
string s = System.Text.Enc oding.UTF8.GetS tring(b);

String to stream:

string s = "whatever";
byte[] b = System.Text.Enc oding.UTF8.GetB ytes(s);
MemoryStream ms = new MemoryStream(b) ;
That's a way which is almost guaranteed to lose data. Serialization
with BinaryFormatter produces opaque binary data, which may very well
not be a valid UTF-8 encoded string.

To convert arbitrary binary data to a string and back, I'd use
Convert.ToBase6 4String and Convert.FromBas e64String.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Jul 17 '06 #5
Jon Skeet [C# MVP] <sk***@pobox.co mwrote:
Peter Bromberg [C# MVP] <pb*******@yaho o.nospammin.com wrote:
>What you are really asking is how to convert a stream (e.g. MemoryStream) to
a string. If you are using the BinaryFormatter the MemoryStream you serialize
to or from can be converted to / from a string as follows:

Stream to string:

byte[] b = MyMemoryStream. ToArray();
string s = System.Text.Enc oding.UTF8.GetS tring(b);

String to stream:

string s = "whatever";
byte[] b = System.Text.Enc oding.UTF8.GetB ytes(s);
MemoryStream ms = new MemoryStream(b) ;

That's a way which is almost guaranteed to lose data. Serialization
with BinaryFormatter produces opaque binary data, which may very well
not be a valid UTF-8 encoded string.

To convert arbitrary binary data to a string and back, I'd use
Convert.ToBase6 4String and Convert.FromBas e64String.
I posted a code snippet using just what you discribe ... look elsewhere in
this thread. Encoding binary data as string often leaves "nulls" and other
characters that string code often considers "end of string" (like /0 in
ASCII), and thus should be avoided ... Base64 does a fine job of avioding it.

--
Thomas T. Veldhouse
Key Fingerprint: 2DB9 813F F510 82C2 E1AE 34D0 D69D 1EDC D5EC AED1

Jul 17 '06 #6
Jon,
Good point. It's so easy when you are focused on spitting out a quick
example for somebody, to pass over some basics.
Peter

--
Co-founder, Eggheadcafe.com developer portal:
http://www.eggheadcafe.com
UnBlog:
http://petesbloggerama.blogspot.com


"Jon Skeet [C# MVP]" wrote:
Peter Bromberg [C# MVP] <pb*******@yaho o.nospammin.com wrote:
What you are really asking is how to convert a stream (e.g. MemoryStream) to
a string. If you are using the BinaryFormatter the MemoryStream you serialize
to or from can be converted to / from a string as follows:

Stream to string:

byte[] b = MyMemoryStream. ToArray();
string s = System.Text.Enc oding.UTF8.GetS tring(b);

String to stream:

string s = "whatever";
byte[] b = System.Text.Enc oding.UTF8.GetB ytes(s);
MemoryStream ms = new MemoryStream(b) ;

That's a way which is almost guaranteed to lose data. Serialization
with BinaryFormatter produces opaque binary data, which may very well
not be a valid UTF-8 encoded string.

To convert arbitrary binary data to a string and back, I'd use
Convert.ToBase6 4String and Convert.FromBas e64String.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Jul 17 '06 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
5823
by: Ian Tompsett | last post by:
H I was wondering if it possible for an object to serialize/deserialize itself from XML. I'd be guessing that it would need to use the XmlSerializer class, but that seems to want to create a brand new object when deserializing. In my case I have an existing object that I'd like to pass some XML to for the object to repopulate its member variables. Similarly I'd like it to be able to populate an XML string from the values of its member...
2
11676
by: Hollywood | last post by:
After doing a search through google's archives of this list, I didn't see what I was looking for so here goes... Is it possible to serialize/deserialize multiple objects from a single XML file? I was looking to use the XML serialization to be able to translate complex XML elements in a single XML file through XML serialization as opposed to using SAX and coding my own serializer. However, the XML Serialization API appears to only...
0
3215
by: Rajesh Cheedalla | last post by:
Hi All, I have a class View, defined with a property called Parameters which is of type class ControlParameters. View class is used serialize/deserialize view.xml. User may define a new class VideoControl that is inherited from ControlParameters and use the view class to create .xml file. The problem I am running into is, at times deserializing, throws an exception saying that type expected is ControlParameters and not...
1
2107
by: Roberto Carriquiry | last post by:
I am writeing a webService that needs to recieve a CDO.Person object as a parameter. but when I run it I have a runtime error. Cannot serialize member CDO.PersonClass.DataSource of type CDO.IDataSource because it is an interface I assume that something is wrong with the serialization of this object. Does anyone have experience in this subject? thanks
0
1764
by: Fred Heida | last post by:
Hi Al, i have a funny problem.. i you can call it funny.. what i have is 2 assemblies, the first one does nothing other then Application.Run(new MyForm())
3
8043
by: Eric | last post by:
I need to send an object between nodes on a network. Each node currently communicates fine with sending strings around but I can't figure out how to deserialize objects using the same basic infrastructure. I'm currently using MS's basic server example for my code: public static void AcceptCallback(IAsyncResult ar) { // Signal the main thread to continue. allDone.Set();
2
2421
by: alexandre martins | last post by:
Every time i try to make Deserialize the computer gives me the folowing error: "End of Stream encountered before parsing was complete" the code that i'm running is simple and is based on an MSDN example. The CODE is BELOW this lines. If you see something wrong or missing please answer. Class declaration:
8
6861
by: Frank Rizzo | last post by:
How do I serialize Font object into a string that I can store in either INI file or the registry (I know it’s a bad thing, but need to do it nevertheless). Then, also, how do I deserialize it from that string back into a font object? Thanks.
0
1331
by: Redowl | last post by:
Hi, I am trying to serialize a business object using xml generated by a FOR XML query and the resulting xml has no root element. I have created my business object using the schema returned from my query's XMLDATA and the xsd tool. However, when i try to serialize the object only the first element gets serialized and I have to use MoveToElement to get all the elements. This is my original code which I am passing in a SqlCommand...
0
8249
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8685
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8633
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8493
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6112
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5570
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4187
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1797
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1493
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.