protobuf3序列化_.NET-3中的序列化

protobuf3序列化

In my previous two articles we discussed

在前两篇文章中,我们讨论了

Binary Serialization and 二进制序列化XML Serialization. In this article we will try to know more about SOAP (Simple Object Access Protocol) serialization. XML序列化 。 在本文中,我们将尝试更多地了解SOAP(简单对象访问协议)序列化。

What is SOAP serialization?

什么是SOAP序列化?

If you have gone through my first article on serialization you will have an idea on what serialization is all about. Serialization is basically conversion of an object into a format which then can be easily transmitted or saved in any format. In SOAP serialization the object is converted to SOAP format (SOAP is based on XML standards). The SOAP XML must conform to the World Wide Web Consortium standards. In SOAP serialization all the member variables (even private members) are serialized to SOAP format. SOAP was developed to bridge the communication gap between the various applications running on different platforms. SOAP can be used in scenarios where you want to transfer your objects across different applications running on different platform/same platform. As long as the objects are serialized to SOAP standards they can be deserialized in any applicaiton running on the same platform or a different platform. Without further delay, let's see some code in action.

如果您阅读了我有关序列化的第一篇文章,您将对序列化的全部内容有一个了解。 序列化基本上是将对象转换为一种格式,然后可以轻松地以任何格式传输或保存该格式。 在SOAP序列化中,对象被转换为SOAP格式(SOAP基于XML标准)。 SOAP XML必须符合万维网联盟标准。 在SOAP序列化中,所有成员变量(甚至私有成员)都被序列化为SOAP格式。 开发SOAP是为了弥合在不同平台上运行的各种应用程序之间的通信鸿沟。 SOAP可用于需要跨不同平台/相同平台上运行的不同应用程序传输对象的场景。 只要将对象序列化为SOAP标准,它们就可以在同一平台或不同平台上运行的任何应用程序中反序列化。 不用再拖延了,让我们来看一些运行中的代码。

First up let's see how to serialize an object to SOAP format. We will take our good old Car class which most of you are very familiar with. The Car class is pasted below.

首先,让我们看看如何将对象序列化为SOAP格式。 我们将参加我们大多数人都非常熟悉的旧汽车课。 Car类粘贴在下面。

public class Car 
{        
    public string Color 
    { get; set; } 
    public string Model 
    { get; set; } 
    public int NoOfDoors 
    { get; set; } 
    public int Price 
    { get; set; } 
    public string CubicCentimeter 
    { get; set; }        
    public CarType Type 
    { get; set; } 
}

We will make use of the above car class for SOAP serialization. The code to serialize a class to SOAP format is similar to XML serialization with a small difference. The code is pasted below.

我们将利用上述汽车类进行SOAP序列化。 将类序列化为SOAP格式的代码与XML序列化相似,只是有一点点差异。 该代码粘贴在下面。

Car bmw3Series = new Car{Model = "BMW 3 Series", Color = "Blue", NoOfDoors = 4,  CubicCentimeter="3500cc"}; 
using (System.IO.Stream soapStream = new System.IO.FileStream("SoapFormat.xml", System.IO.FileMode.OpenOrCreate)) 
{ 
    System.Xml.Serialization.SoapReflectionImporter soapRefImp = new System.Xml.Serialization.SoapReflectionImporter(); 
    System.Xml.Serialization.XmlTypeMapping xmlTypeMapping = 
        soapRefImp.ImportTypeMapping(typeof(Car)); 
    System.Xml.Serialization.XmlSerializer xmlSerializer = 
        new System.Xml.Serialization.XmlSerializer(xmlTypeMapping); 
    xmlSerializer.Serialize(soapStream, bmw3Series); 
}

To serialize an object into SOAP format one can make use of XmlSerilizer class. When we initialize the XmlSerializer class for SOAP serialization instead of passing the type of the object we pass an instance of XmlTypeMapping class. This is the subtle difference. As you can see from the above code we are instantiating XmlTypeMapping object by passing the type of the Car object to the ImportTypeMapping method of SoapReflectionImporter class. SoapReflectionImporter class can be used whenever you want to serialize objects to SOAP formats.

要将对象序列化为SOAP格式,可以使用XmlSerilizer类。 当我们初始化XmlSerializer类以进行SOAP序列化而不是传递对象的类型时,我们传递XmlTypeMapping类的实例。 这是微妙的区别。 从上面的代码中可以看到,我们通过将Car对象的类型传递给SoapReflectionImporter类的ImportTypeMapping方法来实例化XmlTypeMapping对象。 每当您要将对象序列化为SOAP格式时,都可以使用SoapReflectionImporter类。

The SOAP XML generated from the above code for the Car class is pasted below.

从上面的代码中为Car类生成的SOAP XML粘贴在下面。

<?xml version="1.0" ?> 
<Car xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" id="id1"> 
  <Color xsi:type="xsd:string">Blue</Color> 
  <Model xsi:type="xsd:string">BMW 3 Series</Model> 
  <NoOfDoors xsi:type="xsd:int">4</NoOfDoors> 
  <Price xsi:type="xsd:int">0</Price> 
  <CubicCentimeter xsi:type="xsd:string">3500cc</CubicCentimeter> 
</Car>

Another way to serialize objects is by making use of SoapFormatter class. To make use of the SoapFormatter class one has to add a reference to the “System.Runtime.Serialization.Formatters.Soap.dll” assembly. The sample code is pasted below.

序列化对象的另一种方法是使用SoapFormatter类。 要使用SoapFormatter类,必须添加对“ System.Runtime.Serializat”的引用 离子格式 肥皂 dll”程序集。 示例代码粘贴在下面。

using (System.IO.Stream soapStream = new System.IO.FileStream("SoapFormatter.xml", System.IO.FileMode.Create)) 
{ 
    System.Runtime.Serialization.Formatters.Soap.SoapFormatter soapFormatter = 
        new System.Runtime.Serialization.Formatters.Soap.SoapFormatter(); 
    soapFormatter.Serialize(soapStream, bmw3Series); 
}

The SOAP xml generated from the above code is pasted below.

从上面的代码生成的SOAP xml粘贴在下面。

<SOAP-ENV:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema- 
instance" xmlns:xsd="http://www.w3.org/2001/ 
XMLSchema" Xmlns:SOAP-ENC="http://schemas. 
xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV= 
"http://schemas.xmlsoap.org/soap/envelope/" xmlns:clr="http://schemas.microsoft.com/soap 
/encoding/clr/1.0" SOAP-ENV:encodingStyle= 
"http://schemas.xmlsoap.org/soap/encoding/"> 
<SOAP-ENV:Body> 
<a1:Car id="ref-1" xmlns:a1="http://schemas.microsoft.com/clr/ 
nsassem/SoapSerialization/SerializationSample% 
2C%20Version%3D1.0.0.0%2C%20Culture%3Dneutral% 
2C%20PublicKeyToken%3Dnull"> 
<_x003C_Color_x003E_k__BackingField id="ref-3">Blue</_x003C_Color_x003E_k__ 
BackingField> 
<_x003C_Model_x003E_k__BackingField id="ref-4">BMW 3 Series</_x003C_Model_x003E_k__BackingField> 
<_x003C_NoOfDoors_x003E_k__BackingField>4 
</_x003C_NoOfDoors_x003E_k__BackingField> 
<_x003C_Price_x003E_k__BackingField>0 
</_x003C_Price_x003E_k__BackingField> 
<_x003C_CubicCentimeter_x003E_k__BackingField id="ref-5">3500cc</_x003C_CubicCentimeter_ 
x003E_k__BackingField> 
</a1:Car> 
</SOAP-ENV:Body> 
</SOAP-ENV:Envelope>

I would not recommend using SoapFormatter class as this class is obsolete from .NET 3.5 version. Also SoapFormatter class doesn’t support serialization of generic collections.

我不建议使用SoapFormatter类,因为该类已从.NET 3.5版本中淘汰。 同样,SoapFormatter类不支持通用集合的序列化。

That's pretty much how objects can be serialized to SOAP format. As in the case with XML serialization there may be situation where you would like to control the way objects are serialized to SOAP format. This can be very much useful when you are using webservices where you would like to take control of the way your objects are serialized. The following are some of the attributes which can be applied to control object serialization.

这几乎就是将对象序列化为SOAP格式的方式。 与XML序列化一样,您可能希望控制将对象序列化为SOAP格式的方式。 当您使用Web服务来控制对象的序列化方式时,这可能非常有用。 以下是一些可以应用于控制对象序列化的属性。

SoapAttribute

SoapAttribute

One can apply “SoapAttribute” to convert the property or field as a XML attribute rather than as a XML node which is the normal behavior. If you want to change the attribute name, and don’t want it to be same as that of the property name, you can make use of the “AttributeName” property along with “SoapAttribute”. To provide a namespace to the xml attribute you can make use of the “Namespace” property. When you provide namespace it has to abide by w3 guidelines. As a general practice, we provide urls as namespace. If you want to provide the data type to the attribute again, that can be specified with the help DataType property. Sample code is pasted below.

可以应用“ SoapAttribute”将属性或字段转换为XML属性,而不是正常行为的XML节点。 如果要更改属性名称,并且不想与属性名称相同,则可以将“ AttributeName”属性与“ SoapAttribute”一起使用。 要为xml属性提供名称空间,可以使用“名称空间”属性。 提供名称空间时,必须遵守w3准则。 通常,我们提供网址作为名称空间。 如果要再次为属性提供数据类型,则可以使用help DataType属性来指定。 示例代码粘贴在下面。

public class Car 
{        
   [System.Xml.Serialization.SoapAttribute (AttributeName="CarColor", DataType="string", Namespace="http://car")] 
    public string Color 
    { get; set; } 
    public string Model 
    { get; set; } 
    public int NoOfDoors 
    { get; set; } 
    public int Price 
    { get; set; } 
    public string CubicCentimeter 
    { get; set; }           
}

The serialized XML after applying the “SoapAttribute” is pasted below.

应用“ SoapAttribute”之后的序列化XML粘贴在下面。

<?xml version="1.0"?> 
<Car xmlns:xsi="http://www.w3.org/2001/XMLSchema-inst 
ance"xmlns:xsd="http://www.w3.org/2001/XMLSchema" id="id1"d1p1:CarColor="Blue" xmlns:d1p1="http://car"> 
  <Model xsi:type="xsd:string">BMW 3 Series</Model> 
  <NoOfDoors xsi:type="xsd:int">4</NoOfDoors> 
  <Price xsi:type="xsd:int">0</Price> 
  <CubicCentimeter xsi:type="xsd:string"> 
3500cc</CubicCentimeter> 
</Car>

From the above pasted XML you can see how the Color property has been added as a SOAP attribute to the Car node.

从上面粘贴的XML中,您可以看到如何将Color属性作为SOAP属性添加到Car节点。

SoapElement

肥皂元素

SoapElement can be used to control the xml element’ attributes. Using the SoapElement attribute on a public property/field will convert the property/field to a XML element. The properties that can be used with SoapElement are ElementName, DataType,  and IsNullable.

SoapElement可用于控制xml元素的属性。 在公共属性/字段上使用SoapElement属性会将属性/字段转换为XML元素。 可以与SoapElement一起使用的属性是ElementName,DataType和IsNullable。

With ElementName one can provide a Name to the element, if you don’t want the SOAP XML element name to be same as that of the property/field name.

如果您不希望SOAP XML元素名称与属性/字段名称相同,则使用ElementName可以为元素提供名称。

DataType will help you to specify the SOAP XML schema data type.

DataType将帮助您指定SOAP XML模式数据类型。

IsNullable specifies whether a SOAP XML element node should be generated if the property/field is null. If the IsNullable value is true then an empty XML element with xsi:nil attribute set to true will be generated for properties/fields having null value, else no XML element node will be generated. As we have learned in XML serialization, if IsNullable is used in SOAP serialization it won’t throw any error even if it is used along with value type objects. In SOAP serialization if you have set IsNullable to true then for value type it will create a node with a default value assigned to it. For example, if you have used IsNullable for int data type and boolean data type then the SOAP xml will have nodes with 0 and false as their default value, if they are not initialized. Sample code with these implementation and the SOAP XML is pasted below.

IsNullable指定如果属性/字段为null,是否应生成SOAP XML元素节点。 如果IsNullable值为true,则将为具有空值的属性/字段生成xsi:nil属性设置为true的空XML元素,否则将不生成XML元素节点。 正如我们在XML序列化中所了解的那样,如果IsNullable用于SOAP序列化,则即使将其与值类型对象一起使用也不会引发任何错误。 在SOAP序列化中,如果将IsNullable设置为true,则对于值类型,它将创建一个为其分配了默认值的节点。 例如,如果已将IsNullable用于int数据类型和boolean数据类型,则SOAP xml将具有未初始化的节点,其节点的默认值是0和false。 下面粘贴了具有这些实现和SOAP XML的示例代码。

public class Car 
{ 
    [System.Xml.Serialization.SoapElement 
(ElementName = "CarColor", IsNullable = true)] 
        public string Color 
        { get; set; } 
        [System.Xml.Serialization.SoapElement (ElementName="CarModel")] 
        public string Model 
        { get; set; } 
        public int NoOfDoors 
        { get; set; } 
        [System.Xml.Serialization.SoapElement (ElementName = "CarPrice", IsNullable = true)] 
        public int Price 
        { get; set; }        
        public string CubicCentimeter 
        { get; set; }           
}

//Car object to be serialized. 
Car bmw3Series = new Car{Model = "BMW 3 Series", NoOfDoors = 4, CubicCentimeter="3500cc"};

//Serialized SOAP XML 
<?xml version="1.0"?> 
<Car xmlns:xsi="http://www.w3.org/2001/XMLSchema 
- instance" xmlns:xsd="http://www.w3.org/2001/ 
XMLSchema" id="id1"> 
  <CarColor xsi:nil="true" /> 
  <CarModel xsi:type="xsd:string">BMW 3 Series</CarModel> 
  <NoOfDoors xsi:type="xsd:int">4</NoOfDoors> 
  <CarPrice xsi:type="xsd:int">0</CarPrice> 
  <CubicCentimeter xsi:type="xsd:string">3500cc</CubicCentimeter> 
</Car>

From the above xml one can see there is “xsi:nill” XML attribute set to true for “CarColor” node as we have applied “IsNullable” true. Also notice “CarPrice” node having “0” as its value. Since we have used “IsNullable,” it is generating a node with a default value.

从上面的xml中可以看到,由于我们已将“ IsNullable” true应用于“ CarColor”节点,因此将“ xsi:nill” XML属性设置为true。 另请注意,“ CarPrice”节点的值为“ 0”。 由于我们使用了“ IsNullable”,因此它将生成具有默认值的节点。

SoapEnum

肥皂枚举

Can be used to describe how Enum needs to be serialized. It has only one property named Name, so that you can specify what should be the name of the particular Enum value. Sample code is pasted below.

可以用来描述如何枚举Enum。 它只有一个名为Name的属性,因此您可以指定特定Enum值的名称。 示例代码粘贴在下面。

public enum CarType 
{ 
    [System.Xml.Serialization.SoapEnum(Name = "CompactCar")] 
    SmallCar, 
   [System.Xml.Serialization.SoapEnum(Name= "CompactSedan")] 
    CS, 
    Sedan, 
    SportsCar, 
    Suv 
}

If the “Name” property is specified then the enum’ member will have the name specified in the “Name” property else it will default to the member name.

如果指定了“名称”属性,则枚举成员将具有在“名称”属性中指定的名称,否则它将默认为成员名称。

SoapIgnore

肥皂忽略

If you want a public field or property not to be serialized then you can make use SoapIgnore attribute. This will prevent a particular public field or property from being serialized. SoapIgnore doesn’t have any property. The serialized XML and SoapIgnore attribute applied to Color property of the Car class is pasted below.

如果希望不对公共字段或属性进行序列化,则可以使用SoapIgnore属性。 这将防止特定的公共领域或财产被序列化。 SoapIgnore没有任何属性。 下面粘贴了应用于Car类的Color属性的序列化XML和SoapIgnore属性。

public class Car 
{ 
    [System.Xml.Serialization.SoapIgnore] 
    public string Color 
    { get; set; } 
    [System.Xml.Serialization.SoapElement (ElementName="CarModel")] 
    public string Model 
    { get; set; } 
    public int NoOfDoors 
    { get; set; } 
    [System.Xml.Serialization.SoapElement(ElementName = "CarPrice", IsNullable = true)] 
    public int Price 
    { get; set; }        
    public string CubicCentimeter 
    { get; set; }           
}

//Car object which needs to be serialized 
Car bmw3Series = new Car{Model = "BMW 3 Series", 
NoOfDoors = 4, Color="Blue", CubicCentimeter="3500cc"};

//Serialized XML with SoapIgnore attribute applied. 
<?xml version="1.0"?> 
<Car xmlns:xsi="http://www.w3.org/2001/ 
XMLSchema-instance" xmlns:xsd="http://www.w3.org 
/2001/XMLSchema" id="id1"> 
  <CarModel xsi:type="xsd:string">BMW 3 Series</CarModel> 
  <NoOfDoors xsi:type="xsd:int">4</NoOfDoors> 
  <CarPrice xsi:type="xsd:int">0</CarPrice> 
  <CubicCentimeter xsi:type="xsd:string">3500cc</CubicCentimeter> 
</Car>500cc</CubicCentimeter> 
</Car>

From the above pasted SOAP XML one can note that Color attribute is missing because of the usage of SoapIgnore.

从上面粘贴的SOAP XML中可以注意到,由于使用了SoapIgnore,因此缺少了Color属性。

SoapInclude

肥皂包括

SoapInclude can be used to specify the derived classes to be included in the SOAP format. For example, you have Car class and other classes like “CompactCar”, “Sedan” etc are deriving from Car class then you can make use SoapInclude. Suppose you have a class called CarCollection, where you have a property called CarInstance which is a generic collection of base type Car. When the CarCollection object is serialized one has to tell the compiler what classes the collection can hold or derives from. If one is not specifying the inherited classes using the SoapInclude attribute, the serialization process throws the following error.

SoapInclude可用于指定要包含在SOAP格式中的派生类。 例如,您有Car类,而其他类(例如“ CompactCar”,“ Sedan”等)是从Car类派生的,则可以使用SoapInclude。 假设您有一个名为CarCollection的类,其中有一个名为CarInstance的属性,该属性是基本类型Car的通用集合。 当CarCollection对象被序列化时,必须告诉编译器该集合可以包含或派生哪些类。 如果未使用SoapInclude属性指定继承的类,则序列化过程将引发以下错误。

InvalidOperationException inner exception: "The type SoapSerialization.CompactCar was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically."

InvalidOperationException内部异常:“类型SoapSerialization.CompactC 没料到ar。 使用XmlInclude或SoapInclude属性可以指定静态未知的类型。”

To avoid the above error you can use SoapInclude attribute. A sample code is pasted below.

为避免上述错误,可以使用SoapInclude属性。 下面粘贴了示例代码。

//Derived classes. 
public class CompactCar : Car 
{ 
    public string SomeProperty 
        { get; set; } 
}

public class Sedan : Car 
{ 
    public int SedanCapacity 
        { get; set; } 
} 
\*Class has a generic collection of type car. One has to use SoapInclude to tell the serializer that the class can have classes of type CompactCar and Sedan.*/ 
[System.Xml.Serialization.SoapInclude(typeof(CompactCar)), 
        System.Xml.Serialization.SoapInclude(typeof(Sedan))]    
public class CarCollection 
{          
        public System.Collections.Generic.List<Car> CarInstance 
        { get; set; } 
}

Sometimes using the SoapInclude attribute may not solve the problem rather it can throw a new error. The error with inner exception is pasted below.

有时使用SoapInclude属性可能无法解决问题,但是会引发新的错误。 内部异常的错误粘贴在下面。

System.InvalidOperationExc eption: "There was an error generating the XML document."

System.InvalidOperationException: "Token StartElement in state Epilog would result in an invalid XML document."

System.InvalidOperationExc eption:“生成XML文档时出错。”

System.InvalidOperationExc eption:“处于Epilog状态的令牌StartElement将导致无效的XML文档。”

To solve this you need to add a start element and end element before and after the serialized SOAP xml using the XmlTextWriter’ WriteStartElement and WriteEndElement methods, respectively. The logic behind this is to add a root node. The SOAP serialization code is modified and pasted below.

为了解决这个问题,您需要分别使用XmlTextWriter的WriteStartElement和WriteEndElement方法在序列化SOAP xml之前和之后添加开始元素和结束元素。 其背后的逻辑是添加根节点。 SOAP序列化代码在下面进行了修改和粘贴。

using (System.IO.Stream soapStream = new System.IO.FileStream("SoapFormat.xml", 
    System.IO.FileMode.Create)) 
{ 
    using (System.Xml.XmlTextWriter xmlWriter = new System.Xml.XmlTextWriter(soapStream, System.Text.Encoding.UTF8)) 
    { 
        System.Xml.Serialization.SoapReflectionImporter soapRefImp = 
            new System.Xml.Serialization.SoapReflectionImporter(); 
        System.Xml.Serialization.XmlTypeMapping xmlTypeMapping = 
            soapRefImp.ImportTypeMapping(typeof(CarCollection)); 
        System.Xml.Serialization.XmlSerializer xmlSerializer = 
            new System.Xml.Serialization.XmlSerializer(xmlTypeMapping); 
        xmlWriter.WriteStartElement("carRoot"); 
        xmlSerializer.Serialize(xmlWriter, carCol);                     
        xmlWriter.WriteEndElement(); 
    }                
}

Deserializing a SOAP XML

反序列化SOAP XML

Deserializing an SOAP XML is pretty simple and similar to the serialization logic. You need to create an instance of “SoapReflectionImporter” class and use the “ImportTypeMapping” method of “SoapReflectionImporter” to create an instance of “XmlTypeMapping” class. Once these things are done, create an instance of “XmlSerializer” class by passing the “XmlTypeMapping” object as one of the parameters. After this call, use the Deserialize method of the “XmlSerializer” class. The sample code is pasted below.

反序列化SOAP XML非常简单,并且类似于序列化逻辑。 您需要创建“ SoapReflectionImporter”类的实例,并使用“ SoapReflectionImporter”的“ ImportTypeMapping”方法创建“ XmlTypeMapping”类的实例。 完成这些操作后,通过传递“ XmlTypeMapping”对象作为参数之一来创建“ XmlSerializer”类的实例。 调用之后,使用“ XmlSerializer”类的Deserialize方法。 示例代码粘贴在下面。

System.Xml.Serialization.SoapReflectionImporter soapReflImp = 
                        new System.Xml.Serialization.SoapReflectionImporter(); 
System.Xml.Serialization.XmlTypeMapping xmlTypeMap = 
        soapReflImp.ImportTypeMapping(typeof(CarCollection)); 
System.Xml.Serialization.XmlSerializer xmlSerial = 
        new System.Xml.Serialization.XmlSerializer(xmlTypeMap); 
using (System.Xml.XmlTextReader xmlTextReader = new System.Xml.XmlTextReader("SoapFormat.xml")) 
{ 
    /*Needed to read the root element. In the serialization code we have added the "carRoot" element.*/ 
    xmlTextReader.ReadStartElement("carRoot"); 
    CarCollection carColl = (CarCollection)xmlSerial.Deserialize(xmlTextReader); 
    xmlTextReader.ReadEndElement(); 
}

One can see from the above code that we are using “ReadStartElement” method of “XmlTextReader” class. This is done because we have manually added the “carRoot” element by making use of “WriteStartElement” method of “XmlTextWriter” while serializing the object. If “ReadStartElement” method is not used then the following error will be thrown.

从上面的代码中可以看到我们正在使用“ XmlTextReader”类的“ ReadStartElement”方法。 这样做是因为我们在序列化对象时通过使用“ XmlTextWriter”的“ WriteStartElement”方法手动添加了“ carRoot”元素。 如果未使用“ ReadStartElement”方法,则将引发以下错误。

System.InvalidOperationExc eption: "There is an error in XML document (1, 2)."

Inner exception - System.InvalidOperationException: "<carRoot xmlns=''> was not expected."

System.InvalidOperationExc eption:“ XML文档(1、2)中存在错误。”

内部异常-System.InvalidOperationExc eption:“未预期<carRoot xmlns =”>。

So that’s about SOAP serialization. Next we will see how to write custom serializers so that we can take control of serialization, till then try to learn more.

这就是关于SOAP序列化的内容。 接下来,我们将看到如何编写自定义序列化程序,以便我们可以控制序列化,然后再尝试了解更多信息。

The original article with comments and discussion can be found here.

带有评论和讨论的原始文章可以在这里找到。

翻译自: https://www.experts-exchange.com/articles/4479/Serialization-in-NET-3.html

protobuf3序列化

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java有很多种序列化序列化的方式,其性能最好的之一就是Google开源的Protobuf(Protocol Buffers)。 下面是使用Protobuf进行序列化和反序列化的步骤(基于Maven项目): 1. 在pom.xml文件添加Protobuf依赖: ``` <dependency> <groupId>com.google.protobuf</groupId> <artifactId>protobuf-java</artifactId> <version>3.17.3</version> </dependency> ``` 2. 定义.proto文件,例如: ``` syntax = "proto3"; package com.example.protobuf; option java_package = "com.example.protobuf"; option java_outer_classname = "PersonProto"; message Person { string name = 1; int32 age = 2; repeated string phoneNumbers = 3; } ``` 3. 使用protoc命令将.proto文件编译成Java类,例如: ``` protoc --java_out=src/main/java src/main/resources/person.proto ``` 4. 在Java代码使用生成的Person类进行序列化和反序列化,例如: ``` import com.example.protobuf.PersonProto.Person; // 序列化 Person person = Person.newBuilder() .setName("John") .setAge(30) .addPhoneNumbers("123456789") .addPhoneNumbers("987654321") .build(); byte[] data = person.toByteArray(); // 反序列化 Person person2 = Person.parseFrom(data); System.out.println(person2.getName()); System.out.println(person2.getAge()); System.out.println(person2.getPhoneNumbersList()); ``` 注意,在实际使用,需要根据具体的业务需求来定义.proto文件,并使用生成的对应Java类进行序列化和反序列化。同时,由于Protobuf是二进制序列化方式,使用时需要注意数据的兼容性和版本控制。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值