Serialização - Converter num string "hexa"

<< Click to Display Table of Contents >>

Navigation:  Funções > Serialização >

Serialização - Converter num string "hexa"

Previous pageReturn to chapter overviewNext page

Introdução

 

Exemplo de como converter um Objeto em um byte[] e depois num string (formatado em hexa) que pode ser usado para gravar em arquivo, enviar por sockets...

A vantagem de converter em HEXA é que pode ser usado em cookies, session, etc

 

Saída

 

Original:                                                                                                                                                                                               
Zelda Williams, 30,  Mulher                                                                                                                                                                             
---------------                                                                                                                                                                                         
                                                                                                                                                                                                        
Serializada:                                                                                                                                                                                            
0001000000FFFFFFFF01000000000000000C020000004A436F6E736F6C654170706C69636174696F6E312C2056657273696F6E3D312E302E302E302C2043756C747572653D6E65757472616C2C205075626C69634B6579546F6B656E3D6E756C6C050100
000006506573736F6103000000153C4E6F6D653E6B5F5F4261636B696E674669656C64163C49646164653E6B5F5F4261636B696E674669656C64173C47656E65726F3E6B5F5F4261636B696E674669656C6401000408045469706F020000000200000006
030000000E5A656C64612057696C6C69616D731E00000005FCFFFFFF045469706F010000000776616C75655F5F000802000000010000000B                                                                                        
---------------                                                                                                                                                                                         
                                                                                                                                                                                                        
Novo objeto:                                                                                                                                                                                            
Zelda Williams, 30,  Mulher                                                                                                                                                                             

 

Using geral

 

using System;

using System.IO;

using System.Runtime.Serialization.Formatters.Binary;

using System.Text;

using System.Globalization;

 

Classe estática que faz as conversões

 

public static class Funcao

{

  public static byte[] ConverteObjectEmByte(Object obj)

   {

      if (obj == null)

          return null;

 

      BinaryFormatter bf = new BinaryFormatter();

 

      MemoryStream ms = new MemoryStream();

 

      //cria um array de bytes através do objeto obj

       bf.Serialize(ms, obj);

 

      //recebe o array referente ao objeto obj

      byte[] ret = ms.ToArray();

 

      return ret;

   }

 

  public static Object ConverteByteEmObject(byte[] bytes)

   {

      MemoryStream memStream = new MemoryStream();

      BinaryFormatter binForm = new BinaryFormatter();

      //grava na stream o array de bytes passado como parâmetro

       memStream.Write(bytes, 0, bytes.Length);

      //modifica a posição de início da stream (posição zero)

       memStream.Seek(0, SeekOrigin.Begin);

      //converte a stream em um object

      Object obj = (Object)binForm.Deserialize(memStream);

      return obj;

   }

 

  public static string ByteArrayToStr(byte[] array)

   {

      StringBuilder sb = new StringBuilder();

      foreach (byte b in array)

       {

           sb.Append(b.ToString("X2"));

       }

      return sb.ToString();

   }

 

  public static byte[] StrToByteArray(string hexString)

   {

      if ((hexString.Length & 1) != 0)

       {

          throw new ArgumentOutOfRangeException("hexString", hexString, "hexString must contain an even number of characters.");

       }

 

      byte[] result = new byte[hexString.Length / 2];

 

      for (int i = 0; i < hexString.Length; i += 2)

       {

           result[i / 2] = byte.Parse(hexString.Substring(i, 2), NumberStyles.HexNumber);

       }

 

      return result;

   }

}

 

Modelo

 

public enum Tipo

{

   Homem, Mulher

}

 

[Serializable]

public class Pessoa

{

  public string Nome { get; set; }

  public int Idade { get; set; }

  public Tipo Genero { get; set; }

 

  public Pessoa()

   {

   }

 

  public Pessoa(string nome, int idade, Tipo genero)

   {

      this.Nome = nome;

      this.Idade = idade;

      this.Genero = genero;

   }

 

  public override string ToString()

   {

      return Nome + ", " + Idade.ToString() + ", " + (Genero == Tipo.Homem ? " Homem" : " Mulher");

   }

}

 

Programa principal

 

class Program

{

  static void Main(string[] args)

   {

      Pessoa zelda = new Pessoa("Zelda Williams", 30, Tipo.Mulher);

      Console.WriteLine("Original:");

      Console.WriteLine(zelda);

      Console.WriteLine("---------------\n");

 

      // serializa no formato array-hexa

      string zelda_str = Funcao.ByteArrayToStr(Funcao.ConverteObjectEmByte(zelda));

      Console.WriteLine("Serializada:");

      Console.WriteLine(zelda_str);

      Console.WriteLine("---------------\n");

 

      // deserializada

      Pessoa z = (Pessoa)Funcao.ConverteByteEmObject(Funcao.StrToByteArray(zelda_str));

      Console.WriteLine("Novo objeto:");

      Console.WriteLine(z);

      Console.ReadLine();

   }

}