Serializing and deserializing objects into files

In this recipe, we will learn about serialization. Serialization is the process of transforming data structures or—in our case—objects into files that can be read later by the same, or another, computer (phone) in order to create an exact replica of the object that was serialized. The possibilities are endless with serialization because you can use it for storage and communication purposes. End-users can actually send (serialized) objects to each other. You might have found the previous recipe trivial, and you are right, it is trivial. However, we can use the file to store serialized objects, which can be used for almost every purpose. Serialization will happen in two separate classes. Indeed, we first have to create a C# class that we wish to serialize and obviously deserialize. Second, we will effectively play with the serialization in the MainActivity class.

Getting ready

For this recipe we will continue to use the project created in the previous recipe.

How to do it...

  1. Create a new C# class and name it personal:

    The following code sample shows the newly created person class. There are several particularities in this class declaration that must not be ignored.

    using System;
    using Android.App;
    using Android.Content;
    using Android.Runtime;
    using Android.Views;
    using Android.Widget;
    using Android.OS;
    using System.Xml.Serialization;
    
    namespace OnPhoneData {
      [XmlRoot("Person")]
      [Serializable]
      public class Person {
        #region IXmlSerializable Members
        public string Name { get; set; }
        #endregion
      }
    }

    The first one is using System.Xml.Serialization; without which serialization isn't possible at all. Indeed, this contains everything we may need for serialization purposes. The second particularity is the presence of [XmlRoot("Person")] and [Serializable] annotations. As serialization takes place in the XML file, you have to define the root name of this XML file. Therefore, the first annotation defines it. The second one enables the serialization for this particular class. While the first annotation is optional, without the second one, all attempts in serializing the person class will fail. Finally, last but not least, the #region IXmlSerializable Members and #endregion encapsulate the class' attributes you want to persist.

  2. Serialize the person objects:

    In the following code sample, which takes place in the MainActivity class' OnCreate() method, we use the MemoryStream() method as StreamWriter. This allows us to get rid of file-writing permissions in case we just want to send the persisted file to another client/server. Then, we create an XmlSerializer instance, which takes into an argument the type of the class we wish to serialize. In our case, the method typeof(Person) is used as an argument. We now have an XmlSerializer instance capable of serializing person objects. We will not describe the two statements following the creation of the serializer as they are pure and very simple object manipulations in C#. The last statement, however, deserves some explanation. The XmlSerializer class offers the Serialize() method, which requires a StreamWriter and an object to serialize. We give them both with the ms and Person variable.

    using Android.App;
    using Android.Content;
    using Android.Runtime;
    using Android.Views;
    using Android.Widget;
    using Android.OS;
    using System.Xml.Serialization;
    using System.IO;
    
    [Activity (Label = "OnPhoneData", MainLauncher = true)]
    public class MainActivity : Activity {
      protected override void OnCreate (Bundle bundle) {
        base.OnCreate (bundle);
        SetContentView (Resource.Layout.Main);
        using (var ms = new MemoryStream()) {
          XmlSerializer mySerializer = new XmlSerializer (typeof(Person));
          var Person = new Person ();
          Person.Name = "Mathieu";
          mySerializer.Serialize (ms, Person);
        }
      }
    }

    At this point, you can compile and deploy your application to the emulator. However, nothing will tell you if the serialization went well. Obviously, Xamarin Studio will, for sure, tell you if something went wrong. Therefore, we will seize the opportunity to instantly deserialize our object and print the result on some component of the graphical interface.

  3. Deserialize objects:

    In order to deserialize our newly serialized object, we have to add the following code after our serialization, but when it is still in use. The following code sample shows the complete code and highlights the parts related to the deserialization:

    protected override void OnCreate (Bundle bundle) {
      base.OnCreate (bundle);
      SetContentView (Resource.Layout.Main);
      using (var ms = new MemoryStream()) {
        XmlSerializer mySerializer = new XmlSerializer (typeof(SomeData));
        var someData = new Person ();
        someData.Name = "Mathieu";
        mySerializer.Serialize (ms, someData);
        ms.Position = 0;
        Person deserialize = (Person)mySerializer.Deserialize (ms);
        Button button = FindViewById<Button> (Resource.Id.myButton);
        button.Text = deserialize.Name;
      }
    }

As we are not using a real StreamWriter, we have to specifically set the position at which the MemoryStream instance should be, in order to read the correct data. Forgetting this statement will certainly result in a Null Exception while reading. Then, using the same XmlSerializer object and our StreamReader set at the position 0, we invoke the Deserialize() method. This method returns an object, therefore, we have to cast the return into a Person object. Finally, as we did many times in Chapter 1, Getting Started and in Chapter 6, Populating Your GUI with Data, we retrieve a reference to a button and set the button's text with the Name value of the newly affected Person object.

The following screenshot shows us the result of the serializing/deserializing process we saw in the previous recipe:

How to do it...

As shown in the preceding screenshot, the button does have Mathieu as text. This value comes from an object that has been created, populated, serialized, and finally deserialized.

How it works...

For serialization, generated files are XML based and therefore human-readable and modifiable. Indeed, the previous sample will result in the following file:

<?xml version="1.0"?>
<Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Name>Mathieu</Name>
</Person>

As you can see, this is very simple, and in case you have to, you could modify files corresponding to serialized objects. Here's the JSON version of the same serialization:

{
  "Person": {
    "-xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
    "-xmlns:xsd": "http://www.w3.org/2001/XMLSchema",
    "Name": "Mathieu"
  }
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.230.82