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

 using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Xml.Serialization;
using System.Reflection;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization; namespace LighTake.Infrastructure.Common
{
/// <summary>
/// 序列化及反序列化的辅助类
/// </summary>
public static class SerializeUtil
{ /// <summary>
/// 将对象序列化为二进制字节
/// </summary>
/// <param name="obj">待序列化的对象</param>
/// <returns></returns>
public static byte[] SerializeToBinary(object obj)
{
byte[] bytes = new byte[];
using (MemoryStream memoryStream = new MemoryStream())
{
BinaryFormatter bformatter = new BinaryFormatter();
bformatter.Serialize(memoryStream, obj);
memoryStream.Seek(, ); if (memoryStream.Length > bytes.Length)
{
bytes = new byte[memoryStream.Length];
}
bytes = memoryStream.ToArray();
}
return bytes;
} /// <summary>
/// 将文件对象序列化到文件中
/// </summary>
/// <param name="obj">待序列化的对象</param>
/// <param name="path">文件路径</param>
/// <param name="fileMode">文件打开模式</param>
public static void SerializeToBinary(object obj, string path, FileMode fileMode)
{
using (FileStream fs = new FileStream(path, fileMode))
{
// Construct a BinaryFormatter and use it to serialize the data to the stream.
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(fs, obj);
}
} /// <summary>
/// 将文件对象序列化到文件中
/// </summary>
/// <param name="obj">待序列化的对象</param>
/// <param name="path">文件路径</param>
public static void SerializeToBinary(object obj, string path)
{
SerializeToBinary(obj, path, FileMode.Create);
} /// <summary>
/// 将对象序列化为XML字符串
/// </summary>
/// <param name="obj">待序列化的对象</param>
/// <returns>XML字符串</returns>
public static string SerializeToXml(object obj)
{
string xml = "";
using (MemoryStream memoryStream = new MemoryStream())
{
XmlSerializer serializer = new XmlSerializer(obj.GetType());
serializer.Serialize(memoryStream, obj);
memoryStream.Seek(, );
xml = Encoding.UTF8.GetString(memoryStream.ToArray());
} return xml;
} public static string SerializeToXml(object obj, XmlSerializerNamespaces namespaces)
{
if (obj == null)
return null; if (namespaces == null)
{
namespaces = new XmlSerializerNamespaces();
namespaces.Add(string.Empty, string.Empty);
} string xml = "";
using (MemoryStream memoryStream = new MemoryStream())
{
XmlSerializer serializer = new XmlSerializer(obj.GetType());
serializer.Serialize(memoryStream, obj, namespaces);
memoryStream.Seek(, );
xml = Encoding.UTF8.GetString(memoryStream.ToArray());
} return xml;
} public static string SerializeToXml(object obj, XmlSerializerNamespaces namespaces, XmlAttributeOverrides attrs)
{
if (namespaces == null)
{
namespaces = new XmlSerializerNamespaces();
namespaces.Add(string.Empty, string.Empty);
} string xml = "";
using (MemoryStream memoryStream = new MemoryStream())
{
XmlSerializer serializer = new XmlSerializer(obj.GetType(), attrs);
serializer.Serialize(memoryStream, obj, namespaces);
memoryStream.Seek(, );
xml = Encoding.UTF8.GetString(memoryStream.ToArray());
} return xml;
} /// <summary>
/// 将对象序列化为XML字符串并保存到文件
/// </summary>
/// <param name="obj">待序列化的对象</param>
/// <param name="path">保存的文件路径</param>
/// <param name="fileMode">文件打开模式</param>
public static void SerializeToXmlFile(object obj, string path, FileMode fileMode)
{
using (FileStream fileStream = new FileStream(path, fileMode))
{
// Construct a BinaryFormatter and use it to serialize the data to the stream.
XmlSerializer serializer = new XmlSerializer(obj.GetType());
serializer.Serialize(fileStream, obj);
}
} /// <summary>
/// 将对象序列化为XML字符串并保存到文件
/// </summary>
/// <param name="obj">待序列化的对象</param>
/// <param name="path">保存的文件路径</param>
public static void SerializeToXmlFile(object obj, string path)
{
SerializeToXmlFile(obj, path, FileMode.Create);
} /// <summary>
/// 从XML文件中反序列化为Object对象
/// </summary>
/// <param name="type">对象的类型</param>
/// <param name="path">XML文件</param>
/// <returns>反序列化后得到的对象</returns>
public static object DeserializeFromXmlFile(Type type, string path)
{
object result = new object();
using (FileStream fileStream = new FileStream(path, FileMode.Open))
{
XmlSerializer serializer = new XmlSerializer(type);
result = serializer.Deserialize(fileStream);
} return result;
} /// <summary>
/// 从XML文件中反序列化为对象
/// </summary>
/// <param name="type">对象的类型</param>
/// <param name="xml">XML字符串</param>
/// <returns>反序列化后得到的对象</returns>
public static object DeserializeFromXml(Type type, string xml)
{
object result = new object();
XmlSerializer serializer = new XmlSerializer(type);
result = serializer.Deserialize(new StringReader(xml)); return result;
} /// <summary>
/// 从XML文件中反序列化为对象
/// </summary>
public static T DeserializeFromXml<T>(string xml)
{
T result = default(T);
var serializer = new XmlSerializer(typeof(T));
result = (T)serializer.Deserialize(new StringReader(xml)); return result;
} public static T DeserializeFromXml<T>(string xml, XmlAttributeOverrides attrs)
{
T result = default(T);
var serializer = new XmlSerializer(typeof(T), attrs);
result = (T)serializer.Deserialize(new StringReader(xml)); return result;
} /// <summary>
/// 从二进制字节中反序列化为对象
/// </summary>
/// <param name="type">对象的类型</param>
/// <param name="bytes">字节数组</param>
/// <returns>反序列化后得到的对象</returns>
public static object DeserializeFromBinary(Type type, byte[] bytes)
{
object result = new object();
using (MemoryStream memoryStream = new MemoryStream(bytes))
{
BinaryFormatter serializer = new BinaryFormatter();
result = serializer.Deserialize(memoryStream);
} return result;
} /// <summary>
/// 从二进制文件中反序列化为对象
/// </summary>
/// <param name="type">对象的类型</param>
/// <param name="path">二进制文件路径</param>
/// <returns>反序列化后得到的对象</returns>
public static object DeserializeFromBinary(Type type, string path)
{
object result = new object();
using (FileStream fileStream = new FileStream(path, FileMode.Open))
{
BinaryFormatter serializer = new BinaryFormatter();
result = serializer.Deserialize(fileStream);
} return result;
} /// <summary>
/// 获取对象的转换为二进制的字节大小
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static long GetByteSize(object obj)
{
long result;
BinaryFormatter bFormatter = new BinaryFormatter();
using (MemoryStream stream = new MemoryStream())
{
bFormatter.Serialize(stream, obj);
result = stream.Length;
}
return result;
} /// <summary>
/// 克隆一个对象
/// </summary>
/// <param name="obj">待克隆的对象</param>
/// <returns>克隆的一个新的对象</returns>
public static object Clone(object obj)
{
object cloned = null;
BinaryFormatter bFormatter = new BinaryFormatter();
using (MemoryStream memoryStream = new MemoryStream())
{
try
{
bFormatter.Serialize(memoryStream, obj);
memoryStream.Seek(, SeekOrigin.Begin);
cloned = bFormatter.Deserialize(memoryStream);
}
catch //(Exception e)
{
;
}
} return cloned;
} /// <summary>
/// 从文件中读取文本内容
/// </summary>
/// <param name="path">文件路径</param>
/// <returns>文件的内容</returns>
public static string ReadFile(string path)
{
string content = string.Empty;
using (StreamReader reader = new StreamReader(path))
{
content = reader.ReadToEnd();
} return content;
} /// <summary>
/// 读取嵌入资源的文本内容
/// </summary>
/// <param name="fileWholeName">包含命名空间的嵌入资源文件名路径</param>
/// <returns>文件中的文本内容</returns>
public static string ReadFileFromEmbedded(string fileWholeName)
{
string result = string.Empty; Assembly assembly = Assembly.GetEntryAssembly();
using (TextReader reader = new StreamReader(assembly.GetManifestResourceStream(fileWholeName)))
{
result = reader.ReadToEnd();
} return result;
} #region /*序列化和反序列化*/ public static string ToXml<T>(this T value)
{
XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
namespaces.Add(string.Empty, string.Empty);
XmlSerializer serializer = new XmlSerializer(typeof(T));
StringWriter textWriter = new StringWriter(new StringBuilder(), CultureInfo.CurrentCulture);
serializer.Serialize(textWriter, value, namespaces);
string str = textWriter.ToString();
textWriter.Close();
return str;
} public static T FromXml<T>(this string xml)
{
T local = default(T);
if (!string.IsNullOrWhiteSpace(xml))
{
try
{
TextReader textReader = new StringReader(xml);
XmlSerializer serializer = new XmlSerializer(typeof(T));
local = (T)serializer.Deserialize(textReader);
textReader.Close();
return local;
}
catch
{
}
}
return local;
} /// <summary>
/// 将对象序列化为JSON
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj"></param>
/// <returns></returns>
public static string ToJson<T>(this T obj)
{
if ((object)obj == null)
{
return string.Empty;
}
return JsonConvert.SerializeObject(obj);
} /// <summary>
/// 将JSON字符串反序列化为对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="jsonString"></param>
/// <returns></returns>
public static T FromJson<T>(this string jsonString)
{
if (jsonString.IsNullOrWhiteSpace())
{
return default(T);
}
return JsonConvert.DeserializeObject<T>(jsonString);
} #endregion
}
}

JSON和XML格式与对象的序列化及反序列化的辅助类的更多相关文章

  1. 利用JavaScriptSerializer类 进行Json对象的序列化和反序列化和过滤

    项目下载:JavaScriptSerializer_对JSON对象序列化与反序列化及过滤器 利用<JavascriptSerializer类> 进行Json对象的序列化和反序列化 1. 首 ...

  2. Java对象的序列化与反序列化-Json篇

    说到Java对象的序列化与反序列化,我们首先想到的应该是Java的Serializable接口,这玩意在两个系统之间的DTO对象里面可能会用到,用于系统之间的数据传输.或者在RPC(远程方法调用)时可 ...

  3. .NetCore获取Json和Xml格式的配置信息

    本篇将和大家分享的是:如何获取Json和Xml格式的配置信息,主要介绍的是Configuration扩展方法的使用,因为netcore的web应用在Startup中已经默认嵌入appsettings. ...

  4. (记录)Jedis存放对象和读取对象--Java序列化与反序列化

    一.理论分析 在学习Redis中的Jedis这一部分的时候,要使用到Protostuff(Protobuf的Java客户端)这一序列化工具.一开始看到序列化这些字眼的时候,感觉到一头雾水.于是,参考了 ...

  5. Java对象的序列化与反序列化

    序列化与反序列化 序列化 (Serialization)是将对象的状态信息转换为可以存储或传输的形式的过程.一般将一个对象存储至一个储存媒介,例如档案或是记亿体缓冲等.在网络传输过程中,可以是字节或是 ...

  6. 一文带你全面了解java对象的序列化和反序列化

    摘要:这篇文章主要给大家介绍了关于java中对象的序列化与反序列化的相关内容,文中通过详细示例代码介绍,希望能对大家有所帮助. 本文分享自华为云社区<java中什么是序列化和反序列化?>, ...

  7. java中对象的序列化和反序列化

    [对象的序列化和反序列化 ] 1.定义:序列化--将对象写到一个输出流中.反序列化则是从一个输入流中读取一个对象.类中的成员必须是可序列化的,而且要实现Serializable接口,这样的类的对象才能 ...

  8. Java对象的序列化和反序列化[转]

    Java基础学习总结--Java对象的序列化和反序列化 一.序列化和反序列化的概念 把对象转换为字节序列的过程称为对象的序列化.把字节序列恢复为对象的过程称为对象的反序列化. 对象的序列化主要有两种用 ...

  9. 【Java IO流】对象的序列化和反序列化

    对象的序列化和反序列化 1)对象序列化,就是将Object对象转换成byte序列,反之叫对象的反序列化. 2)序列化流(ObjectOutputStream),是字节的过滤流—— writeObjec ...

随机推荐

  1. LightGBM与评分卡

    调参策略 最大化 off_ks + 0.8(off_ks-train_ks) import pandas as pd from sklearn.metrics import roc_auc_score ...

  2. SOCKET_CONNECT_TIMEOUT is the timeout for the connection to be established and SOCKET_TIMEOUT

    https://github.com/niwinz/django-redis/blob/master/doc/content.adoc#32-socket-timeout 3.2. Socket ti ...

  3. 7个最好的Java机器学习开发库

    摘要:现如今,拥有深度学习和机器学习领域的技术是科技界的趋势之一,并且企业则希望雇佣一些拥有良好的机器学习知识背景的程序开发工程师.本文将介绍一些目前流行的.强大的基于Java的机器学习库,希望给大家 ...

  4. flutter编译ios的时候需要进行的操作:

    pod install  执行这个命令,安装依赖

  5. 123457123456#0#---com.threeapp.ErTongShuXueKoSuan01----儿童宝宝数学口算01

    com.threeapp.ErTongShuXueKoSuan01----儿童宝宝数学口算01

  6. SpringCloud学习成长之路 六 cloud配置中心

    一.简介 在分布式系统中,由于服务数量巨多,为了方便服务配置文件统一管理,实时更新,所以需要分布式配置中心组件.在Spring Cloud中,有分布式配置中心组件spring cloud config ...

  7. Microsoft Visual Studio(VS)启动报安装过程中无法运行

    开机启动VS提示无法运行,很可能VS正在更新,可以等待几分钟更新完成,再次运行VS. 也可以把更新进程结束,进程名:VSIXAutoUpdate.exe

  8. cut截取数据

    参考文档 https://blog.csdn.net/caoshunxin01/article/details/79355566 [root@kube-node3 ~]# cat tab_space. ...

  9. MySQL从.ibd文件中恢复数据

    首先,在MySQL命令行下执行如下命令可以查看MySQL中存放数据的位置: show global variables like "%datadir%"; 我这里的执行结果: +- ...

  10. 【Leetcode_easy】766. Toeplitz Matrix

    problem 766. Toeplitz Matrix solution1: class Solution { public: bool isToeplitzMatrix(vector<vec ...