search
HomeBackend DevelopmentC#.Net TutorialDetailed explanation of serialization and deserialization using Protobuffer in .NET

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; }
    }

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();
        }
   }
}

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();
        }
   }

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
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
在Java中,我们如何使用flexjson序列化对象列表?在Java中,我们如何使用flexjson序列化对象列表?Sep 05, 2023 pm 11:09 PM

Flexjson是一个轻量级库,用于序列化和反序列化Java对象>和来自JSON格式。我们可以使用JSONSerializer类的serialize()方法序列化对象列表。此方法可以对目标实例执行浅层序列化。我们需要将列表类型的对象列表作为参数传递给serialize()方法。语法publicStringserialize(Objecttarget)示例importflexjson.JSONSerializer;importjava.util.*;publicclassJsonSerial

如何使用Java中的flexjson库序列化一个map?如何使用Java中的flexjson库序列化一个map?Aug 26, 2023 pm 08:13 PM

Flexjson是一个轻量级库,用于将Java对象序列化为JSON格式以及反序列化为JSON格式。我们还可以使用JSONSerializer类的serialize()方法来序列化Map,它对目标实例执行浅层序列化。语法publicStringserialize(Objecttarget)示例importflexjson.JSONSerializer;importjava.util.*;publicclassJsonSerializeMapTest{&nbsp;&nbsp;publ

如何使用Java中的Jackson库对属性的顺序进行序列化?如何使用Java中的Jackson库对属性的顺序进行序列化?Aug 28, 2023 pm 12:45 PM

@JsonPropertyOrder是在类级别使用的注释。它采用字段列表作为属性,该列表定义字段在对象JSON序列化生成的字符串中出现的顺序。可以首先序列化注释声明中包含的属性(按定义的顺序),然​​后序列化定义中未包含的任何属性。语法public@interfaceJsonPropertyOrder示例importcom.fasterxml.jackson.core.*;importcom.fasterxml.jackson.databind.*;importcom.fasterxml.jac

C++ 函数库如何进行序列化和反序列化?C++ 函数库如何进行序列化和反序列化?Apr 18, 2024 am 10:06 AM

C++函数库序列化和反序列化指南序列化:创建输出流并将其转换为存档格式。将对象序列化到存档中。反序列化:创建输入流并将其从存档格式恢复。从存档中反序列化对象。实战示例:序列化:创建输出流。创建存档对象。创建对象并将其序列化到存档中。反序列化:创建输入流。创建存档对象。创建对象并从存档中反序列化。

Java序列化如何影响性能?Java序列化如何影响性能?Apr 16, 2024 pm 06:36 PM

序列化对Java性能的影响:序列化过程依赖于反射,会显著影响性能。序列化需要创建字节流存储对象数据,导致内存分配和处理成本。序列化大对象会消耗大量内存和时间。序列化后的对象在网络上传输时会增加负载量。

PHP数据处理技巧:如何使用serialize和unserialize函数实现数据序列化与反序列化PHP数据处理技巧:如何使用serialize和unserialize函数实现数据序列化与反序列化Jul 29, 2023 am 10:49 AM

PHP数据处理技巧:如何使用serialize和unserialize函数实现数据序列化与反序列化序列化和反序列化是在计算机科学中常用的数据处理技巧之一。在PHP中,我们可以使用serialize()和unserialize()函数来实现数据的序列化和反序列化操作。本文将为您详细介绍如何使用这两个函数,并提供相关代码示例。一、什么是序列化和反序列化在计算机编

Java 中接口和抽象类的序列化和反序列化Java 中接口和抽象类的序列化和反序列化May 02, 2024 am 08:33 AM

接口无法直接序列化,抽象类可以序列化但前提是不包含非静态、非瞬态字段或覆盖writeObject()和readObject()方法,具体实例可通过实现接口的具体类或覆盖writeObject()和readObject()方法的抽象类实现。

golang函数类型的序列化与反序列化golang函数类型的序列化与反序列化Apr 29, 2024 am 08:15 AM

GoLang函数类型可通过encoding/gob包实现序列化和反序列化。序列化:注册自定义类型并使用gob.NewEncoder将函数类型编码为字节数组。反序列化:使用gob.NewDecoder从字节数组反序列化函数类型。

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.