天天看點

.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