zoukankan      html  css  js  c++  java
  • .Net 序列化和反序列化SerializerHelper

      开始以为SerializerHelper类是项目中已包含的,后来在别的解决方案中测试代码才发现SerializerHelper类是自己写的。

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Text;
    using System.IO;
    using System.Xml.Serialization;
    using Newtonsoft.Json;
    
    /// <summary>
    /// SerializerHelper 的摘要说明
    /// </summary>
    public static class SerializerHelper
    {
        /// <summary>
        /// 反序列化XML文件
        /// </summary>
        public static T LoadFromXmlFile<T>(string filepath) where T : class
        {
            using (FileStream stream = new FileStream(filepath, FileMode.Open, FileAccess.Read))
            {
                XmlSerializer serializer = new XmlSerializer(typeof(T));
                return (T)serializer.Deserialize(stream);
            }
        }
    
        /// <summary>
        /// 反序列化XML字符串
        /// </summary>
        public static T LoadFromXmlString<T>(string xml) where T : class
        {
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            byte[] bytes = Encoding.UTF8.GetBytes(xml);
    
            using (MemoryStream stream = new MemoryStream(bytes))
            {
                return (T)serializer.Deserialize(stream);
            }
        }
    
        /// <summary>
        /// 序列化XML对象
        /// </summary>
        public static string SaveToXmlString<T>(T entity) where T : class
        {
            using (MemoryStream stream = new MemoryStream())
            {
                XmlSerializer serializer = new XmlSerializer(typeof(T));
                serializer.Serialize(stream, entity);
                return Encoding.UTF8.GetString(stream.ToArray());
            }
        }
    
        /// <summary>
        /// 序列化Json对象
        /// </summary>
        public static string ToJsonString(object obj)
        {
            return ToJsonString<object>(obj);
        }
    
        /// <summary>
        /// 序列化Json对象
        /// </summary>
        public static string ToJsonString<T>(T obj) where T : class
        {
            string text = JsonConvert.SerializeObject(obj);
            return text;
        }
    
        /// <summary>
        /// 反序列化Json字符串
        /// </summary>
        public static T ToJsonObject<T>(string text) where T : class
        {
            T obj = (T)JsonConvert.DeserializeObject(text, typeof(T));
            return obj;
        }
    }

     Newtonsoft.Json.dll的下载地址(找了半天不知道在哪里添加附件所以只能放我上传的路径了):

    https://files.cnblogs.com/files/swjian/Newtonsoft.Json.rar
  • 相关阅读:
    delphi Int64Rec 应用实例
    PerformEraseBackground 擦除背景(ThemeServices)
    Delphi 的 Bit
    delphi 关于 "高位" 与 "低位"
    PByte和PChar的关系
    执行控制台程序并且获得它的输出结果
    Console下Pause效果的函数
    ByteType字符串中判断是否英文
    窗体包括标题作为一个位图复制到剪贴板
    inf 启动
  • 原文地址:https://www.cnblogs.com/swjian/p/7866922.html
Copyright © 2011-2022 走看看