Does C# have native serialization?

Asked

Viewed 243 times

15

In PHP there is a language proper data serialization feature. I mean: I’m not talking about using JSON or XML, but I speak of a serialization in a format that is proper to the language.

For example, if I want to serialize a array or a objeto, I can do that easily.

serialize(['a' => 1, 'b' => 2])

The result will be:

'a:2:{s:1:"a";i:1;s:1:"b";i:2;}'

If I want to deserialize this data, I can invoke the function unserialize to convert this data to a valid PHP value.

Behold:

unserialize('a:2:{s:1:"a";i:1;s:1:"b";i:2;}')

The result will be:

[
  "a" => 1,
  "b" => 2,
]

In conclusion, this is a specific format, where the language itself will understand which data needs to be converted.

In C# is there something similar? Is there some form of native data serialization of the language?

Note: Just to reinforce: I’m not talking about JSON or XML, but in a native way, as demonstrated in the PHP example.

  • Note that serialization can be any format, a language can adopt Json by default for example: https://en.wikipedia.org/wiki/Comparison_of_data_serialization_formats

3 answers

16


Yes, it is possible, the . NET provides this possibility through reflection. But don’t worry, you don’t have to do anything too much, just say what you want to be serializable. Just use the attribute Serializable that the framework know what to do. And if you need some members not to participate in the serialization you can use NonSerializable.

Serialization can be obtained in different formats depending on the need, either text or binary (example) which is considered more or less obsolete, due to the difficulties it imposes. It needs some format. If you want to know if there is a format invented by . NET, binary only, in general JSON is used for text.

Obviously some cases need something more customized and the default serialization does not work. Here the solution is to implement the interface ISerializable with the logic that is best suited to what you need.

You don’t always have to ask to serialize or deserialize, the framework used can take care of it for you in cases he knows it is what he needs. Obviously he will not do it in non-serializable types.

There are some external libraries that are more performative and many people give preference to the native. One of them is the Newtonsoft Json.NET, the most used nowadays (which is used by some frameworks). Another is the protobuf.NET created by an SE employee. But now . NET has a form officer better than all the others at least at some points.

Documentation. And new mechanism.

I do not know deeply the serialization of PHP, but should work very similarly.

  • In Java there is the problem of the version, from one version to another it can change the format and then the serializations of the objects are incompatible. Does C# have that too? (I’m sorry if it’s already answered, I read over it and I don’t know much about C#)

  • @Piovezan depends, has no serialization version problem, can have if you use totally different serializations and has object version problem. That’s not very handy without a mechanism to handle it. These mechanisms usually have some way of dealing with versions and do not give problems easy to solve, but not everything is simple and your application needs to deal with it..

  • That’s it, version of the object, confused.

0

The net dot natively has the BinaryFormatter, Serialization is until fast, but if your object is a very large and complex graph, the deserialization can be slow. For production use usually third party libraries are used.

As already said, just mark the class (and the classes contained) with [Serializable].

/*
    Importe:
    using System.Runtime.Serialization.Formatters.Binary;
*/

SeuObjeto objeto = new SeuObjeto(); // Pode ser qualquer tipo serializavel

BinaryFormatter formatter = new BinaryFormatter();

MemoryStream data = new MemoryStream();

// Para serializar:
formatter.Serialize(data, objeto);

data.Position = 0;

// Para deserializar
objeto = (SeuObjeto)formatter.Deserialize(data);

If you want to delete something from serialization check with [NonSerialized]

Another detail, the Binary Formatter uses layout little endian, You don’t have to worry about that.

-1

Microsoft has adopted Newtonsoft.NET, a third-party package adopted as Official, as the guy responsible for making serializations within the environment . NET.

Its use is extremely simple, just first install the package Json.NET in your project via Nuget Packager Manager or via Packager Manager Console:

PM> Install-Package Newtonsoft.Json

Then to serialize:

Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Sizes = new string[] { "Small" };

string json = JsonConvert.SerializeObject(product);
// {
//   "Name": "Apple",
//   "Expiry": "2008-12-28T00:00:00",
//   "Sizes": [
//     "Small"
//   ]
// }

To deserialize:

string json = @"{
  'Name': 'Bad Boys',
  'ReleaseDate': '1995-4-7T00:00:00',
  'Genres': [
    'Action',
    'Comedy'
  ]
}";

Movie m = JsonConvert.DeserializeObject<Movie>(json);

string name = m.Name;
// Bad Boys

Or using LINQ:

JArray array = new JArray();
array.Add("Manual text");
array.Add(new DateTime(2000, 5, 23));

JObject o = new JObject();
o["MyArray"] = array;

string json = o.ToString();
// {
//   "MyArray": [
//     "Manual text",
//     "2000-05-23T00:00:00"
//   ]
// }

For more information, see the official Json.NET.

  • Hello Thiago, blz? So the question asks for something native and that does not specifically deal with JSON or XML. I think your answer goes against the two premises made in the question, which is why I voted 'no'.

  • @Randrade The fact is that there is nothing native in .NET. Microsoft has adopted the Json.NET lib as official to perform serializations and vice versa. It does not have a specific, proprietary format like PHP, it simply left it to Newtonsoft to define this, and it uses JSON as a serialization format.

  • So if I were to answer exactly, it would be something like "There’s nothing native about it in . NET, nor serializer, nor serialization format". But that doesn’t mean there isn’t something official. And if you’re going to treat Officer as Native, then the answer would be the same: "Install Json.NET as Nuget package and the native format adopted is JSON".

  • @Randrade anyway, thank you for explaining the negative. Few do this, and those who do deserve due recognition. :)

  • 1

    Well, about there not being this is not true. The answer below shows that you have the SerializableAttribute and if you want to think further (and in Json), there is also DataContractJsonSerializer. Both native.

  • 1

    About the part of MS making Json.NET as the official lib and JSON as the official serialization format, I do not know this information. If you have any links talking about this, I would be grateful to you to show me this information.

  • @Randrade About Json.NET being the official, I don’t think there is such a formal announcement, but just make sure that all official Microsoft libs that rely on a serializer use Json.NET as the Official. See dependencies of the package Microsoft Asp.Net Web API.

  • So @Thiago, you’re focusing on JSON (Web API is mostly used for Json nowadays) and AP has emphasized that you’re not wanting an answer on this subject, so my comments. About the notations, Json.NET uses them because they are convenient, but they have no relation to each other. If you look closely, the Serializeattribute is available since version 1.1 of . Net.

  • As the purposes are similar, it was convenient to use. However, Json.NET could create its own attribution for this, as is the case for several unique things in the package. Also remembering that there is even a comparison between 3 Serializers on the Json.NET website itself.

  • I must point out that I agree with the use of it and I think it is the best for this purpose. However, I only emphasize that this was not the question of the AP.

  • 1

    .NET has no native or proprietary serialization format like PHP. The format initially adopted since . NET 1.1 is XML - hence the SerializeAttribute since then. It then adopted JSON as the Official format, and using Json.NET lib as the official serialization lib.

Show 6 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.