什么是数据序列化? [英] What is data serialization?

查看:76
本文介绍了什么是数据序列化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我无法从 维基百科 甚至来自 PHP 手册中的 serialize 函数.我需要知道一些我们需要术语序列化的情况以及没有它的情况如何?换句话说,如果您需要序列化,如果没有序列化,您的代码将缺少一些重要功能.

First of all, I couldn't get clear definition of it from WikiPedia or even from serialize function in the PHP manual. I need to know some cases where we need the term serialization and how things are going without it? In other words, Where you need serialization and without it your code will be missing some important feature.

推荐答案

什么是序列化?

序列化将对象编码为另一种格式.
例如,你在 PHP 中有一个这样的数组:

Serialization encodes objects into another format.
For example you have an array in PHP like this:

$array = array("a" => 1, "b" => 2, "c" => array("a" => 1, "b" => 2));

然后您想将其存储在文件中或发送到其他应用程序.

And then you want to store it in file or send to other application.

有多种格式选择,但思路是一样的:数组必须被编码(或者你可以说翻译"),成文本或字节,可以写入文件或通过网络发送.
例如,在 PHP 中,如果您:

There are several format choices, but the idea is the same: The array has to be encoded (or you could say "translated"), into text or bytes, that can be written to a file or sent via the network.
For example, in PHP, if you:

$data = serialize($array);

你会得到这个:

a:3:{s:1:"a";i:1;s:1:"b";i:2;s:1:"c";a:2:{s:1:"a";i:1;s:1:"b";i:2;}}

这是 PHP 能够理解的 PHP 特定序列化格式,反之亦然,因此您可以使用它来反序列化对象.
例如,您在文件中存储了一个序列化数组,并且希望将其作为数组返回到代码中:

This is PHP's particular serializing format that PHP understands, and it works vice versa, so you are able to use it to deserialize objects.
For example, you stored a serialized array in a file, and you want it back in your code as an array:

$array = unserialize($data);

但您可以选择不同的序列化格式,例如 JSON:

But you could choose a different serialization format, for example, JSON:

$json = json_encode($array);

会给你这个:

{"a":1,"b":2,"c":{"a":1,"b":2}}

结果不仅易于保存、人眼读取或通过网络发送,而且几乎所有其他语言(JavaScript、Java、C#、C++ 等)都可以理解

The result is not only easily saved, read by human eye, or sent via network, but is also understandable by almost every other language (JavaScript, Java, C#, C++, ...)

结论
序列化将对象转换为另一种格式,以防您想存储或共享数据.

Conclusion
Serialization translate objects to another format, in case you want to store or share data.

有没有什么情况,你什么都做不了,只能序列化?

没有.但序列化通常会使事情变得更容易.

No. But serialization usually makes things easier.

JSON 和 PHP 格式是唯一可能的格式吗?
不,不,不,还有一次不.有很多格式.

Are JSON and PHP format the only possible formats?
No, no, no and one more time no. There are plenty of formats.

  • XML 具有 SOAP、WSDL 等后继(具有特定用途)
  • 字节、Protobuf 等
  • Yaml
  • ...
  • ...
  • 您自己的格式(您可以创建自己的序列化格式并使用它,但大多数情况下这是一件大事而且不值得)

这篇关于什么是数据序列化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆