[Serializable]
public class Pessoa
{
public string Nome { get; set; }
public string Cpf { get; set; }
}
- Is there only one kind of serialization ?
- What are the alternatives for not needing serializing an object?
[Serializable]
public class Pessoa
{
public string Nome { get; set; }
public string Cpf { get; set; }
}
In computing science, in the context of data storage and transmission, serialization is the process of saving or transliterating one object into another in a storage medium (such as a computer file or a memory buffer) you can use it for a network connection, either in binary form or in text format such as XML or JSON. This series of bytes can be used to recreate an object with the same internal state as the original.
Source: link (adapted)
No. There are several types of serialization, the difference being the final format of the data representation. For example, using the Json
method, from Newtonsoft.Json
library, you will have a JSON serialization. Using the System.Xml.Serialization.XmlSerializer
object, you can convert (or serialize) an object in XML format.
var objeto = new { nome = "Nome", valor = "Valor" };
return Json(objeto, JsonRequestBehavior.AllowGet);
{ 'nome': 'Nome', 'valor': 'Valor' }
I'm going to use your class:
[Serializable]
public class Pessoa
{
public string Nome { get; set; }
public string Cpf { get; set; }
}
Usage:
var pessoa = new Pessoa { Nome = "Nome", Cpf = "123.456.789-01" };
XmlSerializer x = new XmlSerializer(pessoa.GetType());
x.Serialize(Console.Out, pessoa);
<?xml version="1.0" encoding="IBM437"?>
<pessoa xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3
.org/2001/XMLSchema">
<Nome>Nome</Nome>
<Cpf>123.456.789-01</Cpf>
</pessoa>
Serialization is already implemented in C # for different formats. Serialization should first be viewed as a concept, and then as a language resource.
You can even deploy your serialization to the format you want, but ideally you should use components ready to avoid extra work.
Just complementing the answer already given by @CiganoMorrisonMendez.
Sometimes it's just not possible to avoid serialization:
transmit an object over the network
Pass an object between AppDomains
If you want to save an object to disk
In all these cases, a reference to the living object simply does not make sense.