zoukankan      html  css  js  c++  java
  • JSON和XML格式与对象的序列化及反序列化的辅助类

    下面的代码主要是把对象序列化为JSON格式或XML格式等

      1 using System;
      2 using System.Collections.Generic;
      3 using System.Globalization;
      4 using System.Linq;
      5 using System.Runtime.Serialization.Json;
      6 using System.Text;
      7 using System.Runtime.Serialization.Formatters.Binary;
      8 using System.IO;
      9 using System.Xml.Serialization;
     10 using System.Reflection;
     11 using Newtonsoft.Json;
     12 using Newtonsoft.Json.Serialization;
     13 
     14 namespace LighTake.Infrastructure.Common
     15 {
     16     /// <summary>
     17     /// 序列化及反序列化的辅助类
     18     /// </summary>
     19     public static class SerializeUtil
     20     {
     21 
     22 
     23         /// <summary>
     24         /// 将对象序列化为二进制字节
     25         /// </summary>
     26         /// <param name="obj">待序列化的对象</param>
     27         /// <returns></returns>
     28         public static byte[] SerializeToBinary(object obj)
     29         {
     30             byte[] bytes = new byte[2500];
     31             using (MemoryStream memoryStream = new MemoryStream())
     32             {
     33                 BinaryFormatter bformatter = new BinaryFormatter();
     34                 bformatter.Serialize(memoryStream, obj);
     35                 memoryStream.Seek(0, 0);
     36 
     37                 if (memoryStream.Length > bytes.Length)
     38                 {
     39                     bytes = new byte[memoryStream.Length];
     40                 }
     41                 bytes = memoryStream.ToArray();
     42             }
     43             return bytes;
     44         }
     45 
     46         /// <summary>
     47         /// 将文件对象序列化到文件中
     48         /// </summary>
     49         /// <param name="obj">待序列化的对象</param>
     50         /// <param name="path">文件路径</param>
     51         /// <param name="fileMode">文件打开模式</param>
     52         public static void SerializeToBinary(object obj, string path, FileMode fileMode)
     53         {
     54             using (FileStream fs = new FileStream(path, fileMode))
     55             {
     56                 // Construct a BinaryFormatter and use it to serialize the data to the stream.
     57                 BinaryFormatter formatter = new BinaryFormatter();
     58                 formatter.Serialize(fs, obj);
     59             }
     60         }
     61 
     62         /// <summary>
     63         /// 将文件对象序列化到文件中
     64         /// </summary>
     65         /// <param name="obj">待序列化的对象</param>
     66         /// <param name="path">文件路径</param>
     67         public static void SerializeToBinary(object obj, string path)
     68         {
     69             SerializeToBinary(obj, path, FileMode.Create);
     70         }
     71 
     72         /// <summary>
     73         /// 将对象序列化为XML字符串
     74         /// </summary>
     75         /// <param name="obj">待序列化的对象</param>
     76         /// <returns>XML字符串</returns>
     77         public static string SerializeToXml(object obj)
     78         {
     79             string xml = "";
     80             using (MemoryStream memoryStream = new MemoryStream())
     81             {
     82                 XmlSerializer serializer = new XmlSerializer(obj.GetType());
     83                 serializer.Serialize(memoryStream, obj);
     84                 memoryStream.Seek(0, 0);
     85                 xml = Encoding.UTF8.GetString(memoryStream.ToArray());
     86             }
     87 
     88             return xml;
     89         }
     90 
     91         public static string SerializeToXml(object obj, XmlSerializerNamespaces namespaces)
     92         {
     93             if (obj == null)
     94                 return null;
     95 
     96             if (namespaces == null)
     97             {
     98                 namespaces = new XmlSerializerNamespaces();
     99                 namespaces.Add(string.Empty, string.Empty);
    100             }
    101 
    102             string xml = "";
    103             using (MemoryStream memoryStream = new MemoryStream())
    104             {
    105                 XmlSerializer serializer = new XmlSerializer(obj.GetType());
    106                 serializer.Serialize(memoryStream, obj, namespaces);
    107                 memoryStream.Seek(0, 0);
    108                 xml = Encoding.UTF8.GetString(memoryStream.ToArray());
    109             }
    110 
    111             return xml;
    112         }
    113 
    114         public static string SerializeToXml(object obj, XmlSerializerNamespaces namespaces, XmlAttributeOverrides attrs)
    115         {
    116             if (namespaces == null)
    117             {
    118                 namespaces = new XmlSerializerNamespaces();
    119                 namespaces.Add(string.Empty, string.Empty);
    120             }
    121 
    122             string xml = "";
    123             using (MemoryStream memoryStream = new MemoryStream())
    124             {
    125                 XmlSerializer serializer = new XmlSerializer(obj.GetType(), attrs);
    126                 serializer.Serialize(memoryStream, obj, namespaces);
    127                 memoryStream.Seek(0, 0);
    128                 xml = Encoding.UTF8.GetString(memoryStream.ToArray());
    129             }
    130 
    131             return xml;
    132         }
    133 
    134         /// <summary>
    135         /// 将对象序列化为XML字符串并保存到文件
    136         /// </summary>
    137         /// <param name="obj">待序列化的对象</param>
    138         /// <param name="path">保存的文件路径</param>
    139         /// <param name="fileMode">文件打开模式</param>
    140         public static void SerializeToXmlFile(object obj, string path, FileMode fileMode)
    141         {
    142             using (FileStream fileStream = new FileStream(path, fileMode))
    143             {
    144                 // Construct a BinaryFormatter and use it to serialize the data to the stream.
    145                 XmlSerializer serializer = new XmlSerializer(obj.GetType());
    146                 serializer.Serialize(fileStream, obj);
    147             }
    148         }
    149 
    150         /// <summary>
    151         /// 将对象序列化为XML字符串并保存到文件
    152         /// </summary>
    153         /// <param name="obj">待序列化的对象</param>
    154         /// <param name="path">保存的文件路径</param>
    155         public static void SerializeToXmlFile(object obj, string path)
    156         {
    157             SerializeToXmlFile(obj, path, FileMode.Create);
    158         }
    159 
    160         /// <summary>
    161         /// 从XML文件中反序列化为Object对象
    162         /// </summary>
    163         /// <param name="type">对象的类型</param>
    164         /// <param name="path">XML文件</param>
    165         /// <returns>反序列化后得到的对象</returns>
    166         public static object DeserializeFromXmlFile(Type type, string path)
    167         {
    168             object result = new object();
    169             using (FileStream fileStream = new FileStream(path, FileMode.Open))
    170             {
    171                 XmlSerializer serializer = new XmlSerializer(type);
    172                 result = serializer.Deserialize(fileStream);
    173             }
    174 
    175             return result;
    176         }
    177 
    178         /// <summary>
    179         /// 从XML文件中反序列化为对象
    180         /// </summary>
    181         /// <param name="type">对象的类型</param>
    182         /// <param name="xml">XML字符串</param>
    183         /// <returns>反序列化后得到的对象</returns>
    184         public static object DeserializeFromXml(Type type, string xml)
    185         {
    186             object result = new object();
    187             XmlSerializer serializer = new XmlSerializer(type);
    188             result = serializer.Deserialize(new StringReader(xml));
    189 
    190             return result;
    191         }
    192 
    193         /// <summary>
    194         /// 从XML文件中反序列化为对象
    195         /// </summary>
    196         public static T DeserializeFromXml<T>(string xml)
    197         {
    198             T result = default(T);
    199             var serializer = new XmlSerializer(typeof(T));
    200             result = (T)serializer.Deserialize(new StringReader(xml));
    201 
    202             return result;
    203         }
    204 
    205 
    206         public static T DeserializeFromXml<T>(string xml, XmlAttributeOverrides attrs)
    207         {
    208             T result = default(T);
    209             var serializer = new XmlSerializer(typeof(T), attrs);
    210             result = (T)serializer.Deserialize(new StringReader(xml));
    211 
    212             return result;
    213         }
    214 
    215         /// <summary>
    216         /// 从二进制字节中反序列化为对象
    217         /// </summary>
    218         /// <param name="type">对象的类型</param>
    219         /// <param name="bytes">字节数组</param>
    220         /// <returns>反序列化后得到的对象</returns>
    221         public static object DeserializeFromBinary(Type type, byte[] bytes)
    222         {
    223             object result = new object();
    224             using (MemoryStream memoryStream = new MemoryStream(bytes))
    225             {
    226                 BinaryFormatter serializer = new BinaryFormatter();
    227                 result = serializer.Deserialize(memoryStream);
    228             }
    229 
    230             return result;
    231         }
    232 
    233         /// <summary>
    234         /// 从二进制文件中反序列化为对象
    235         /// </summary>
    236         /// <param name="type">对象的类型</param>
    237         /// <param name="path">二进制文件路径</param>
    238         /// <returns>反序列化后得到的对象</returns>
    239         public static object DeserializeFromBinary(Type type, string path)
    240         {
    241             object result = new object();
    242             using (FileStream fileStream = new FileStream(path, FileMode.Open))
    243             {
    244                 BinaryFormatter serializer = new BinaryFormatter();
    245                 result = serializer.Deserialize(fileStream);
    246             }
    247 
    248             return result;
    249         }
    250 
    251         /// <summary>
    252         /// 获取对象的转换为二进制的字节大小
    253         /// </summary>
    254         /// <param name="obj"></param>
    255         /// <returns></returns>
    256         public static long GetByteSize(object obj)
    257         {
    258             long result;
    259             BinaryFormatter bFormatter = new BinaryFormatter();
    260             using (MemoryStream stream = new MemoryStream())
    261             {
    262                 bFormatter.Serialize(stream, obj);
    263                 result = stream.Length;
    264             }
    265             return result;
    266         }
    267 
    268         /// <summary>
    269         /// 克隆一个对象
    270         /// </summary>
    271         /// <param name="obj">待克隆的对象</param>
    272         /// <returns>克隆的一个新的对象</returns>
    273         public static object Clone(object obj)
    274         {
    275             object cloned = null;
    276             BinaryFormatter bFormatter = new BinaryFormatter();
    277             using (MemoryStream memoryStream = new MemoryStream())
    278             {
    279                 try
    280                 {
    281                     bFormatter.Serialize(memoryStream, obj);
    282                     memoryStream.Seek(0, SeekOrigin.Begin);
    283                     cloned = bFormatter.Deserialize(memoryStream);
    284                 }
    285                 catch //(Exception e)
    286                 {
    287                     ;
    288                 }
    289             }
    290 
    291             return cloned;
    292         }
    293 
    294         /// <summary>
    295         /// 从文件中读取文本内容
    296         /// </summary>
    297         /// <param name="path">文件路径</param>
    298         /// <returns>文件的内容</returns>
    299         public static string ReadFile(string path)
    300         {
    301             string content = string.Empty;
    302             using (StreamReader reader = new StreamReader(path))
    303             {
    304                 content = reader.ReadToEnd();
    305             }
    306 
    307             return content;
    308         }
    309 
    310         /// <summary>
    311         /// 读取嵌入资源的文本内容
    312         /// </summary>
    313         /// <param name="fileWholeName">包含命名空间的嵌入资源文件名路径</param>
    314         /// <returns>文件中的文本内容</returns>
    315         public static string ReadFileFromEmbedded(string fileWholeName)
    316         {
    317             string result = string.Empty;
    318 
    319             Assembly assembly = Assembly.GetEntryAssembly();
    320             using (TextReader reader = new StreamReader(assembly.GetManifestResourceStream(fileWholeName)))
    321             {
    322                 result = reader.ReadToEnd();
    323             }
    324 
    325             return result;
    326         }
    327 
    328         #region  /*序列化和反序列化*/
    329 
    330         public static string ToXml<T>(this T value)
    331         {
    332             XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
    333             namespaces.Add(string.Empty, string.Empty);
    334             XmlSerializer serializer = new XmlSerializer(typeof(T));
    335             StringWriter textWriter = new StringWriter(new StringBuilder(256), CultureInfo.CurrentCulture);
    336             serializer.Serialize(textWriter, value, namespaces);
    337             string str = textWriter.ToString();
    338             textWriter.Close();
    339             return str;
    340         }
    341 
    342         public static T FromXml<T>(this string xml)
    343         {
    344             T local = default(T);
    345             if (!string.IsNullOrWhiteSpace(xml))
    346             {
    347                 try
    348                 {
    349                     TextReader textReader = new StringReader(xml);
    350                     XmlSerializer serializer = new XmlSerializer(typeof(T));
    351                     local = (T)serializer.Deserialize(textReader);
    352                     textReader.Close();
    353                     return local;
    354                 }
    355                 catch
    356                 {
    357                 }
    358             }
    359             return local;
    360         }
    361 
    362         /// <summary>
    363         /// 将对象序列化为JSON
    364         /// </summary>
    365         /// <typeparam name="T"></typeparam>
    366         /// <param name="obj"></param>
    367         /// <returns></returns>
    368         public static string ToJson<T>(this T obj)
    369         {
    370             if ((object)obj == null)
    371             {
    372                 return string.Empty;
    373             }
    374             return JsonConvert.SerializeObject(obj);
    375         }
    376 
    377         /// <summary>
    378         /// 将JSON字符串反序列化为对象
    379         /// </summary>
    380         /// <typeparam name="T"></typeparam>
    381         /// <param name="jsonString"></param>
    382         /// <returns></returns>
    383         public static T FromJson<T>(this string jsonString)
    384         {
    385             if (jsonString.IsNullOrWhiteSpace())
    386             {
    387                 return default(T);
    388             }
    389             return JsonConvert.DeserializeObject<T>(jsonString);
    390         }
    391 
    392         #endregion
    393     }
    394 }
  • 相关阅读:
    Linux 关机和重启命令
    Linux ubuntu安装ftp服务器
    C++ map和unsorted_map底层实现
    C++中的那些容器在使用时,哪些情况下迭代器会失效
    虚函数表的构造
    C++容器 priority_queue,堆的实现
    c++11中的move是否会改变对象的地址
    (转)关于linux中内核编程中结构体的赋值操作(结构体指定初始化)
    无参方法
    类和对象
  • 原文地址:https://www.cnblogs.com/hudean/p/11062892.html
Copyright © 2011-2022 走看看