加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

【FCL】将实体类序列化为xml,Json等格式

发布时间:2020-12-15 22:47:31 所属栏目:百科 来源:网络整理
导读:这里有本博客涉及到的序列化Json和Binary格式数据的Demo:点击打开链接 一、序列化成二进制格式 using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.IO;using System.Runtime.Serialization;using System.Run

这里有本博客涉及到的序列化Json和Binary格式数据的Demo:点击打开链接


一、序列化成二进制格式

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace BinarySerialization
{
    class Program
    {
        static void Main(string[] args)
        {
            Person p = new Person()
            {
                Name = "Jhon",Age = 11
            };
            Person p2 = null;

            using (Stream objStream = new MemoryStream())
            {
                IFormatter formatter = new BinaryFormatter();
                //序列化
                formatter.Serialize(objStream,p);
                
                StreamReader sr = new StreamReader(objStream);
                Console.WriteLine(sr.ReadToEnd());

                //反序列化
                objStream.Seek(0,SeekOrigin.Begin);
                p2 = formatter.Deserialize(objStream) as Person;
            }

            Console.WriteLine("p2.Name={0},p2.Age={1}",p2.Name,p2.Age);
        }
    }

    [Serializable]
    class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }
}


二、序列化成xml格式数据,请参考我的另一篇博文: 点击打开链接


三、WCF-基于数据契约实体类的序列化

1、序列化为Json格式的数据:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Person p = new Person();
            p.Name = "John";
            p.Age = 42;

            MemoryStream stream1 = new MemoryStream();

            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Person));
            ser.WriteObject(stream1,p);

            //显示Json格式数据
            stream1.Position = 0;
            StreamReader sr = new StreamReader(stream1);
            Console.WriteLine("Json from of Person object: ");
            Console.WriteLine(sr.ReadToEnd());

            //反序列化
            stream1.Position = 0;
            Person p2 = (Person)ser.ReadObject(stream1);

            Console.WriteLine("p2.Name={0},p2.Age.ToString());
        }
    }     
    //必须加如下特性,否则不能序列化
    [DataContract]
    class Person
    {
        [DataMember]
        public string Name { get; set; }

        [DataMember]
        public int Age { get; set; }
    }
}
2、序列化成xml,类似上面的例子,需要使用到的类为DataContractSerializer,这里不再赘述。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读