C# vs Java Serialization

R

Ray Mitchell

Hello,

I have two Java applications that exchange serialized
objects. Although I would like to ultimately convert both
to C# it's a pretty monumental task, especially for
someone just learning both langauges. I thought it might
be more reasonable to start with simply converting the
simpler one of the two and getting it to work. I have
used Microsoft's free Java to C# converter to convert most
of the code, but of course I must complete some of the
conversions manually. I have this basic concern,
however: Will the serialization done in C# be the same as
that done in Java? Also, do all Java compilers serialize
the same way for the same source code? How do I determine
exactly what the serialized data looks like, both
theoretically and emperically? I'd like to be able to
view it at the byte level just for general debugging
purposes. (Of course I could use a packet sniffer, but
that's a little too gross even for a hardware person like
me!)

Thanks,
Ray Mitchell
 
E

Eric Johannsen

You have the choice of several serialization formats in C#. No matter which
format you decide to use, you can save the serialized data to a file if you
want to have a look at the structure. The XML serializer creates quite
straightforward, easy to interpret output. The binary serializer requires a
hex editor to play around with of course.

Try something like this:

using System;
using System.IO;
using System.Xml.Serialization;
using System.Collections;
namespace Test
{
[Serializable()]
public class Config
{
const string filename = "C:\\Temp\\config.xml";
private string userID;
public string UserID
{
get { return userID; }
set { userID = value; }
}
public void Save()
{
XmlSerializer ser = new XmlSerializer(typeof(Config));

TextWriter writer = new StreamWriter(filename);
ser.Serialize(writer, this);
writer.Close();
}
public static Config GetConfig()
{
Config cfg;
FileStream fs;
try
{
fs = new FileStream(filename, FileMode.Open);
/* Use the Deserialize method to restore the object's state
with
data from the XML document. */
XmlSerializer ser = new XmlSerializer(typeof(Config));
cfg = (Config) ser.Deserialize(fs);
fs.Close();
}
catch
{
cfg = null;
}
return cfg;
}
}
}

Then use this object from a test program something like this

Config cfg = new Config();
cfg.UserID = "MyTestID";
cfg.Save(); // Look how it is saved in C:\Temp\Config.xml
// ...
Config cfgNew = Config.GetConfig();

I'm not sure about compatibility between Java and C# serialization formats,
but hopefully someone else in the newsgroup can answer that.

Eric
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top