zoukankan      html  css  js  c++  java
  • C# 序列化和反序列化

    1. 序列化和反序列化:

    定义:

      序列化:将对象以字节流的形式保存到磁盘中或者在网络上进行传输;

      反序列化:从字节流中解析出对象,但需要有对象的实例

    用法:

      序列化:Newtonsoft.Json.JsonConvert.SerializeObject(Readings)

      转换前:{ Systolic = {10}, Diastolic = {20}, Pulse = {30} }

      转换后:{"Systolic":"10","Diastolic":"20","Pulse":"30"}  

      反序列化:Newtonsoft.Json.JsonConvert.DeserializeObject(Readings)

    public class ReceiveBGEntity
    {
            public int Systolic { get; set; }
            public int Diastolic { get; set; }
            public int Pulse { get; set; }
    
            public override string ToString()
            {
                return "Systolic:" + Systolic.ToString() + "; Date:" + Diastolic.ToString() + "; Pulse" + Pulse.ToString();
            }
    }
    
    class Program
    {
            static void Main(string[] args)
            {
                string JSON_BG = "{'Systolic':'1','Diastolic':'5','Pulse':'7'}";
                ReceiveBGEntity BG = Newtonsoft.Json.JsonConvert.DeserializeObject<ReceiveBGEntity>(JSON_BG);
                Console.WriteLine(BG.ToString());
                Console.ReadLine();
            }
    }
    View Code

    对于对象序列化和反序列化操作,经常操作的对象有实体对象,集合,DataTale及匿名对象,匿名对象解析方法DeserializeAnonymousType()的使用例子如下所示:

    class Program
    {
            static void Main(string[] args)
            {
                var AnonymousObj = new { ID = 0, Name = string.Empty, Words = string.Empty };
                string Results = Newtonsoft.Json.JsonConvert.SerializeObject(AnonymousObj);
                AnonymousObj = Newtonsoft.Json.JsonConvert.DeserializeAnonymousType("{\"ID\":\"20160427\",\"Name\":\"Tom\",\"Words\":\"Hello are you?\"}", AnonymousObj);
                Console.WriteLine(AnonymousObj.Name+"["+ AnonymousObj.ID + "],"+ AnonymousObj.Words);
                Console.ReadLine();
            }
    }
    View Code
  • 相关阅读:
    DHCP Option 60 的理解
    几种开源分词工具的比較
    推荐交互设计师阅读的一本书
    iOS IAP教程
    艰苦的RAW格式数据恢复之旅
    BestCoder Round #11 (Div. 2) 前三题题解
    罗马数字
    mysql 加入列,改动列,删除列。
    杂项:ASP.NET Web API
    杂项:Web API
  • 原文地址:https://www.cnblogs.com/sccd/p/5436305.html
Copyright © 2011-2022 走看看