0

I got 2 user-defined classes, called Event and Image, Event has a property stored a list of EventImage, called EventImages. And in Image class, there's a byte[] type property which store the byte[] of one Image file.

Here's the definitions of the 2 classes :

[Serializable]
public Class Event
{
    public String Name {get; set;}
    public DateTime EventTime { get; set;}
    public List<Image> EventImages { get; set; }
    ...
}

[Serializable]
public Class Image
{
    public DateTime ImageTime { get; set;}
    public byte[] pData {get; set;}
    ...
}

Now my question is, I want to serialize my Event object to byte[], and I expect that the whole content of it will be serialize, too, but it seems that I failed.

Here's my code to do Serialization :

    public static byte[] ObjectToByteArray(object obj)
    {
        if (obj == null)
        {
            return null;
        }
        else
        {
            BinaryFormatter bF = new BinaryFormatter();
            using (MemoryStream mS = new MemoryStream())
            {
                bF.Serialize(mS, obj);
                return mS.ToArray();
            }
        }
    }

and here's the code for verification :

Console.WriteLine(ObjectToByteArray(Event));
Console.WriteLine(ObjectToByteArray(Event.EventImage));        
Console.WriteLine(ObjectToByteArray(Event.EventImages.FirstOrDefault().pData));

and the results are(just assumption value) : 100 200 300

But I expect the result should be 600(100+200+300), 500(200+300) and 300.

So, I think my serialization doesn't really serialize the whole content, it just serialize properties with Basic Types, but without the nested objects, am I right?

I've searched lots of posts, and I found plenty of answers to similar questions mentioned "XML Serialization", but I'm not sure whether its helpful or not. Need I use that or is there any other better way? Thanks in advance!

8
  • Question, are you intending to deserialize the object at some point or is this for some different purpose? Have you tried deserializing the object and checking the contents against the first object? Side note - (opinion) it seems that the community is generally moving away from binary serialization unless there is a specific reason to use it. If you use a JSON serializer these issues are far easier to debug since you can see the data right in the JSON output. Try using JSON.NET newtonsoft.com/json to serialize it and look at the resulting file. Commented Mar 10, 2016 at 3:06
  • @drobertson Thanks for your advice! I've used JSON format before, and I think that's a charm to serialize and transfer data, too. But the reason that I need to do this is that I need to use some specific library, and it receive only byte array format. I haven't tried to deserialize the result yet, I will try it later, hope that can help. Thanks! Commented Mar 10, 2016 at 3:11
  • 1
    Looking at your code, it is pretty textbook. I don't see any areas where the binary serialization would obviously fail. Interpreting the byte array output is another thing entirely. That just makes my head hurt. Remember that the binary serializer does more than just store your data in a big chunk, it also has metadata properties inside it to describe how to reconstitute the data. You are looking inside the sausage factory with that. Commented Mar 10, 2016 at 3:21
  • One thing stuck in my head from your comment above. You are using a library that expects a byte array format. Does this format have a spec or is it specifically asking for a byte array from a binary serialized object. That is a fairly odd thing to be looking for unless it is a homegrown solution. That said, I have used them for data purposes, but the byte array data was alway built around a data specification. A binary serialized output wouldn't have fit the spec. Commented Mar 10, 2016 at 3:38
  • @drobertson Well, I'm not quiet sure what does the textbook meaning... is my code too simple? Actually, I can't see any part that may cause error in my code, either. Thanks for your mention! I think there's much I need to know about byte[], as you said, Interpreting the byte array output is another thing entirely, maybe I should search regarding another ways, thanks! Commented Mar 10, 2016 at 3:41

1 Answer 1

1

Quickly made a test to check equality. It passes.

Serializes and deserializes correctly.

Conclusion, don't judge whether something is happening or not until you've tested it.

    public static void Run()
    {
        var i = new Image
        {
            ImageTime = DateTime.UtcNow,
            pData = Guid.NewGuid().ToByteArray()
        };

        var e = new Event
        {
            Name = Guid.NewGuid().ToString(),
            EventTime = DateTime.UtcNow,
            EventImages = new List<Image> {i}
        };

        var bytes = ObjectToByteArray(e);
        var e2 = ObjectFromByteArray(bytes);

        Console.WriteLine(e.Equals(e2));
    }

    public static byte[] ObjectToByteArray(object obj)
    {
        if (obj == null)
        {
            return null;
        }

        var bF = new BinaryFormatter();
        using (var mS = new MemoryStream())
        {
            bF.Serialize(mS, obj);
            return mS.ToArray();
        }
    }

    public static object ObjectFromByteArray(byte[] bytes)
    {
        if (bytes == null)
        {
            return null;
        }

        var bF = new BinaryFormatter();
        using (var mS = new MemoryStream(bytes))
        {
            return bF.Deserialize(mS);
        }
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.