Home Backend Development C#.Net Tutorial Detailed explanation of serialization and deserialization using Protobuffer in .NET

Detailed explanation of serialization and deserialization using Protobuffer in .NET

Mar 03, 2017 pm 01:26 PM

Use Protobuffer to implement serialization and deserialization in .NET

1. Go to the official website to download protobuf-net.dll, Official address: http://code.google.com/p/protobuf-net/

2. Build a console application

3. Add class library: protobuf-net.dll to the application.

Sample code:

Prepare an entity class to be tested (note that the class and method must have the protoBuffer serialization feature):

 [ProtoContract]
    public class Student
    {
        [ProtoMember(1)]
        public intStudentId { get; set; }
        [ProtoMember(2)]
        public stringName { get; set; }
        [ProtoMember(3)]
        public stringClassName { get; set; }
    }
Copy after login

Then test this class Serialization and Deserialization

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ProtoBuf;
using ProtoBufferDemo.Entity;
using System.IO;
 
namespace ProtoBufferDemo
{
   class Program
   {
        private const string TestPath = @"D:/1.txt";
        static void Main(string[] args)
        {
            ////////////////////////序列化//////////////////////////////
 
            Student stu = new Student()
            {
                StudentId = 1,
                Name = "zhangsan",
                ClassName = "classOne"
            };
 
            if (!File.Exists(TestPath))
            {
               FileStream fs = File.Create(TestPath,1024, FileOptions.Asynchronous);
               fs.Dispose();
            }
 
            Console.WriteLine("开始序列化并导出到文件...");
            using (Stream s = new FileStream(TestPath,FileMode.Open ,FileAccess.ReadWrite))
            {
                Serializer.Serialize<Student>(s, stu);
                s.Close();
            }
            Console.WriteLine("序列化完毕");
 
            //////////////////////反序列化////////////////////////////
 
            Console.WriteLine("反序列化并输出...");
            using (Stream s = new FileStream(TestPath,FileMode.Open))
            {
                Student st = Serializer.Deserialize<Student>(s);
                Console.WriteLine("studentName:"+ stu.Name + "/r/n" +
                                  "studentId:"+ stu.StudentId + "/r/n" +
                                  "className:" + stu.ClassName);
                s.Close();
            }
 
            Console.Read();
        }
   }
}
Copy after login

Now consider the situation of multiple entities and test itSerializing a collection:

class Program
   {
        private const string TestPath = @"D:/1.txt";
        static void Main(string[] args)
        {
            ////////////////////////序列化//////////////////////////////
 
            List<Student> stu = new List<Student>()
            {
                new Student(){
                StudentId = 1,
                Name = "zhangsan",
                ClassName = "classOne"},
 
                new Student(){StudentId = 2,
                Name = "lisi",
                ClassName = "classTwo"}
            };
 
            if (!File.Exists(TestPath))
            {
                FileStream fs = File.Create(TestPath,1024, FileOptions.Asynchronous);
                fs.Dispose();
            }
 
            Console.WriteLine("开始序列化并导出文件...");
            using (Stream s = new FileStream(TestPath,FileMode.Open, FileAccess.ReadWrite))
            {
                Serializer.Serialize<List<Student>>(s,stu);
                s.Close();
            }
            Console.WriteLine("序列化完毕");
 
            //////////////////////反序列化////////////////////////////
 
            Console.WriteLine("反序列化并输出...");
            using (Stream s = new FileStream(TestPath,FileMode.Open))
            {
                List<Student> sl = Serializer.Deserialize<List<Student>>(s);
 
                foreach (var student in sl)
                {
                    Console.WriteLine("studentName:"+ student.Name + "/r/n" +
                                "studentId:" + student.StudentId + "/r/n" +
                                "class Name:" + student.ClassName);
                }
 
              
                s.Close();
            }
 
            Console.Read();
        }
   }
Copy after login

The above is the detailed explanation of serialization and deserialization using Protobuffer in .NET. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve php deserialization failure How to solve php deserialization failure Oct 11, 2023 am 09:30 AM

Solution to PHP deserialization failure Check the serialized data. Check class definitions, check error logs, update PHP versions and apply security measures, etc. Detailed introduction: 1. Check the serialized data. First check whether the serialized data is valid and conforms to PHP's serialization specification. If the data is damaged or has an incorrect format, you can try to repair it or restore the correct data from backup; 2. Check Class definition, ensure that all classes used in serialized data exist and can be automatically loaded. If the class does not exist or is inaccessible, you can try to repair the class definition, etc.

In Java, how can we serialize a list of objects using flexjson? In Java, how can we serialize a list of objects using flexjson? Sep 05, 2023 pm 11:09 PM

Flexjson is a lightweight library for serializing and deserializing Java objects to and from JSON format. We can serialize a list of objects using the serialize() method of the JSONSerializer class. This method performs shallow serialization on the target instance. We need to pass a list of objects of list type as a parameter to the serialize() method. Syntax publicStringserialize(Objecttarget) example importflexjson.JSONSerializer;importjava.util.*;publicclassJsonSerial

How does Java serialization affect performance? How does Java serialization affect performance? Apr 16, 2024 pm 06:36 PM

The impact of serialization on Java performance: The serialization process relies on reflection, which will significantly affect performance. Serialization requires the creation of a byte stream to store object data, resulting in memory allocation and processing costs. Serializing large objects consumes a lot of memory and time. Serialized objects increase load when transmitted over the network.

PHP data processing skills: How to use the serialize and unserialize functions to implement data serialization and deserialization PHP data processing skills: How to use the serialize and unserialize functions to implement data serialization and deserialization Jul 29, 2023 am 10:49 AM

PHP data processing skills: How to use the serialize and unserialize functions to implement data serialization and deserialization Serialization and deserialization are one of the commonly used data processing skills in computer science. In PHP, we can use the serialize() and unserialize() functions to implement data serialization and deserialization operations. This article will give you a detailed introduction to how to use these two functions and provide relevant code examples. 1. What is serialization and deserialization in computer programming?

How does the C++ function library perform serialization and deserialization? How does the C++ function library perform serialization and deserialization? Apr 18, 2024 am 10:06 AM

C++ Library Serialization and Deserialization Guide Serialization: Creating an output stream and converting it to an archive format. Serialize objects into archive. Deserialization: Creates an input stream and restores it from archive format. Deserialize objects from the archive. Practical example: Serialization: Creating an output stream. Create an archive object. Create and serialize objects into the archive. Deserialization: Create an input stream. Create an archive object. Create objects and deserialize them from the archive.

How to serialize the order of properties using Jackson library in Java? How to serialize the order of properties using Jackson library in Java? Aug 28, 2023 pm 12:45 PM

@JsonPropertyOrder is an annotation used at class level. It takes as an attribute a list of fields that defines the order in which the fields appear in the string generated by the JSON serialization of the object. Properties included in the annotation declaration can be serialized first (in the order they are defined), followed by any properties not included in the definition. Syntax public@interfaceJsonPropertyOrder Example importcom.fasterxml.jackson.core.*;importcom.fasterxml.jackson.databind.*;importcom.fasterxml.jac

Serialization and deserialization of interfaces and abstract classes in Java Serialization and deserialization of interfaces and abstract classes in Java May 02, 2024 am 08:33 AM

Interfaces cannot be serialized directly. Abstract classes can be serialized but only if they do not contain non-static, non-transient fields or override the writeObject() and readObject() methods. Specific instances can be implemented through concrete classes that implement the interface or override writeObject() and readObject. Abstract class implementation of () method.

High performance serialization and deserialization technology in PHP High performance serialization and deserialization technology in PHP Jun 22, 2023 pm 09:34 PM

Serialization is the process of converting data structures or objects into a transmittable data format, while deserialization is the process of restoring these data to the original objects or data structures. In web development, serialization and deserialization technologies are widely used in scenarios such as data transmission, caching, and distributed computing. As a commonly used web back-end development language, how are PHP's built-in serialization and deserialization functions implemented? This article will introduce serialization in PHP

See all articles