分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > IT知识

.Net 序列化和反序列化SerializerHelper

发布时间:2023-09-06 01:25责任编辑:熊小新关键词:暂无标签

  开始以为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

.Net 序列化和反序列化SerializerHelper

原文地址:http://www.cnblogs.com/swjian/p/7866922.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved