已经是Stream,MemoryStream的形式,是不是就unity 不用序列化化了

博客分类:
using System.C
using System.C
using System.D
using System.L
using System.W
using System.Web.S
using System.Web.UI;
using System.Web.UI.HtmlC
using System.Web.UI.WebC
using System.Web.UI.WebControls.WebP
using System.Xml.L
using System.IO;
using System.T
using System.Runtime.Serialization.J
using System.Collections.G
using System.R
using System.Web.Script.S
namespace AjaxTest
public partial class Json : System.Web.UI.Page
protected void Page_Load(object sender, EventArgs e)
//Response.Write(getJsonInfo());
//string strReg = "\\\\";
//strReg = strReg.Replace("\\\\", "\\");
////Response.Write(strReg);
Response.Write(disJsonInfo(getObjectByJson(getJsonInfo())));
Response.Write(JsonInfo.getInfo());
/// &summary&
/// 获取将实体类转换为json数据(目的是为了更快在网页上传递数据)
/// &/summary&
/// &returns&&/returns&
public string getJsonInfo()
UserInfo userInfo = new UserInfo();
//userInfo.strNameInfo = "张三";
//userInfo.intAgeInfo = 23;
//userInfo.intTelInfo = 66666;
//userInfo.strAddrInfo = "北京市";
//userInfo.strPasswordInfo = "yhx.123";
userInfo.strName = "张三";
userInfo.intAge = 23;
userInfo.strPsd = "yhx.123";
userInfo.intTel = 2324;
userInfo.strAddr = "北京市";
//将对象序列化json
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(UserInfo));
//创建存储区为内存流
System.IO.MemoryStream ms = new MemoryStream();
//将json字符串写入内存流中
serializer.WriteObject(ms, userInfo);
System.IO.StreamReader reader = new StreamReader(ms);
ms.Position = 0;
string strRes = reader.ReadToEnd();
reader.Close();
ms.Close();
return strR
/// &summary&
/// 将json数据转换成实体类
/// &/summary&
/// &returns&&/returns&
private static List&UserInfo& getObjectByJson(string jsonString)
// 实例化DataContractJsonSerializer对象,需要待序列化的对象类型
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(List&UserInfo&));
//把Json传入内存流中保存
jsonString = "[" + jsonString + "]";
MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
// 使用ReadObject方法反序列化成对象
object ob = serializer.ReadObject(stream);
List&UserInfo& ls = (List&UserInfo&)
/// &summary&
/// 在页面上显示转换为实体类数据
/// &/summary&
private string
disJsonInfo(List&UserInfo& us)
string strItem = "";
foreach(var item in us )
strItem += item.strName + ":" + item.strPsd + ":" + item.intAge + ":" + item.intTel + ":" + item.strAddr + "&br/&";
return strI
/// &summary&
/// 用户实体类
/// &/summary&
public class UserInfo
public string strName { }
public int intAge { }
public string strPsd { }
//电话号码
public int intTel { }
public string strAddr { }
////构造函数进行初始化
//public UserInfo()
strName = "";
intAge = 0;
strPsd = "";
intTel = 0;
strAddr = "";
///// &summary&
///// 用户名
///// &/summary&
//public string strNameInfo
set { strName = }
get { return strN }
///// &summary&
///// 年龄
///// &/summary&
//public int intAgeInfo
set { intAge = }
get { return intA }
///// &summary&
///// 密码
///// &/summary&
//public string strPasswordInfo
set { strPsd = }
get { return strP }
///// &summary&
///// 电话号码
///// &/summary&
//public int intTelInfo
set { intTel = }
get { return intT }
///// &summary&
///// 地址
///// &/summary&
//public string strAddrInfo
set { strAddr = }
get { return strA }
/// &summary&
/// 将json数据转换成实体类(方法二)
/// &/summary&
public static class JsonInfo
/// &summary&
/// 获取将实体类转换为json数据(目的是为了更快在网页上传递数据)
/// &/summary&
/// &returns&&/returns&
public static string getJsonInfo()
UserInfo userInfo = new UserInfo();
userInfo.strName = "张三";
userInfo.intAge = 23;
userInfo.strPsd = "yhx.123";
userInfo.intTel = 2324;
userInfo.strAddr = "北京市";
//将对象序列化json
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(UserInfo));
//创建存储区为内存流
System.IO.MemoryStream ms = new MemoryStream();
//将json字符串写入内存流中
serializer.WriteObject(ms, userInfo);
System.IO.StreamReader reader = new StreamReader(ms);
ms.Position = 0;
string strRes = reader.ReadToEnd();
reader.Close();
ms.Close();
return strR
/// &summary&
/// &/summary&
/// &returns&&/returns&
public static string getInfo()
string JsonStr = "["+getJsonInfo()+"]";
List&UserInfo&
products = JsonInfo.JSONStringToList&UserInfo&(JsonStr);
string strItem = "";
foreach (var item in products)
strItem += item.strName + ":" + item.strPsd + ":" + item.intAge + ":" + item.intTel + ":" + item.strAddr + "&br/&";
return strI
/// &summary&
/// 返回List集合对象
/// &/summary&
/// &typeparam name="T"&&/typeparam&
/// &param name="JsonStr"&&/param&
/// &returns&&/returns&
public static List&T& JSONStringToList&T&(this string JsonStr)
JavaScriptSerializer Serializer = new JavaScriptSerializer();
List&T& objs = Serializer.Deserialize&List&T&&(JsonStr);
/// &summary&
/// &/summary&
/// &typeparam name="T"&&/typeparam&
/// &param name="json"&&/param&
/// &returns&&/returns&
public static T Deserialize&T&(string json)
T obj = Activator.CreateInstance&T&();
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
return (T)serializer.ReadObject(ms);
浏览 29333
浏览: 102109 次
来自: 江西
(window.slotbydup=window.slotbydup || []).push({
id: '4773203',
container: s,
size: '200,200',
display: 'inlay-fix'本帖子已过去太久远了,不再提供回复功能。&>&FileStream MemoryStream 内存流 文件流 生成客户端
FileStream MemoryStream 内存流 文件流 生成客户端
上传大小:954KB
FileStream MemoryStream 内存流 文件流 生成客户端
FileStream MemoryStream 内存流 文件流 生成客户端
综合评分:3.2(12位用户评分)
下载个数:
{%username%}回复{%com_username%}{%time%}\
/*点击出现回复框*/
$(".respond_btn").on("click", function (e) {
$(this).parents(".rightLi").children(".respond_box").show();
e.stopPropagation();
$(".cancel_res").on("click", function (e) {
$(this).parents(".res_b").siblings(".res_area").val("");
$(this).parents(".respond_box").hide();
e.stopPropagation();
/*删除评论*/
$(".del_comment_c").on("click", function (e) {
var id = $(e.target).attr("id");
$.getJSON('/index.php/comment/do_invalid/' + id,
function (data) {
if (data.succ == 1) {
$(e.target).parents(".conLi").remove();
alert(data.msg);
$(".res_btn").click(function (e) {
var parentWrap = $(this).parents(".respond_box"),
q = parentWrap.find(".form1").serializeArray(),
resStr = $.trim(parentWrap.find(".res_area_r").val());
console.log(q);
//var res_area_r = $.trim($(".res_area_r").val());
if (resStr == '') {
$(".res_text").css({color: "red"});
$.post("/index.php/comment/do_comment_reply/", q,
function (data) {
if (data.succ == 1) {
var $target,
evt = e || window.
$target = $(evt.target || evt.srcElement);
var $dd = $target.parents('dd');
var $wrapReply = $dd.find('.respond_box');
console.log($wrapReply);
//var mess = $(".res_area_r").val();
var mess = resS
var str = str.replace(/{%header%}/g, data.header)
.replace(/{%href%}/g, 'http://' + window.location.host + '/user/' + data.username)
.replace(/{%username%}/g, data.username)
.replace(/{%com_username%}/g, _username)
.replace(/{%time%}/g, data.time)
.replace(/{%id%}/g, data.id)
.replace(/{%mess%}/g, mess);
$dd.after(str);
$(".respond_box").hide();
$(".res_area_r").val("");
$(".res_area").val("");
$wrapReply.hide();
alert(data.msg);
}, "json");
/*删除回复*/
$(".rightLi").on("click",'.del_comment_r', function (e) {
var id = $(e.target).attr("id");
$.getJSON('/index.php/comment/do_comment_del/' + id,
function (data) {
if (data.succ == 1) {
$(e.target).parent().parent().parent().parent().parent().remove();
$(e.target).parents('.res_list').remove()
alert(data.msg);
//填充回复
function KeyP(v) {
var parentWrap = $(v).parents(".respond_box");
parentWrap.find(".res_area_r").val($.trim(parentWrap.find(".res_area").val()));
评论共有6条
资源不错,值得学习
资源不错,值得学习
学习中,还有些不明白。
可以用,还不错
还不错。可以用
在处理序列化DataSet结果集,还是比较管用的,谢谢!
审核通过送C币
delphi xe开发资料及源码
创建者:qq_
Delphi 1.0~7.0合集+文章+代码+控件
创建者:caozhy
Borland Delphi合集
创建者:wuwei666888
上传者其他资源上传者专辑
HTML5 游戏引擎 csdn
Deflexion 游戏开发系列课程
C#多线程控制
VIP会员动态
CSDN下载频道资源及相关规则调整公告V11.10
下载频道用户反馈专区
下载频道积分规则调整V1710.18
spring mvc+mybatis+mysql+maven+bootstrap 整合实现增删查改简单实例.zip
资源所需积分/C币
当前拥有积分
当前拥有C币
为了良好体验,不建议使用迅雷下载
FileStream MemoryStream 内存流 文件流 生成客户端
会员到期时间:
剩余下载个数:
剩余C币:593
剩余积分:0
为了良好体验,不建议使用迅雷下载
积分不足!
资源所需积分/C币
当前拥有积分
您可以选择
程序员的必选
绿色安全资源
资源所需积分/C币
当前拥有积分
当前拥有C币
(仅够下载10个资源)
为了良好体验,不建议使用迅雷下载
资源所需积分/C币
当前拥有积分
当前拥有C币
为了良好体验,不建议使用迅雷下载
资源所需积分/C币
当前拥有积分
当前拥有C币
您的积分不足,将扣除 10 C币
为了良好体验,不建议使用迅雷下载
你当前的下载分为234。
你还不是VIP会员
开通VIP会员权限,免积分下载
你下载资源过于频繁,请输入验证码
您因违反CSDN下载频道规则而被锁定帐户,如有疑问,请联络:!
若举报审核通过,可奖励20下载分
被举报人:
举报的资源分:
请选择类型
资源无法下载
资源无法使用
标题与实际内容不符
含有危害国家安全内容
含有反动色情等内容
含广告内容
版权问题,侵犯个人或公司的版权
*详细原因:
FileStream MemoryStream 内存流 文件流 生成客户端序列化 C#编写的序列化通用类代码 - 为程序员服务
为程序员服务
C#编写的序列化通用类代码
using System.IO;
using System.Runtime.Serialization.Formatters.B
using System.Runtime.Serialization.Formatters.S
using System.T
using System.X
using System.Xml.S
namespace PlatForm.Utilities
public enum SerializedType : ushort
ByteArray = 0,
Object = 1,
String = 2,
Datetime = 3,
= 5, //Makes no sense.
Short = 7,
UShort = 8,
UInt = 10,
Long = 11,
ULong = 12,
Float = 13,
Double = 14,
CompressedByteArray = 255,
CompressedObject = 256,
CompressedString = 257,
public class SerializeHelper
public SerializeHelper()
#region XML序列化
/// &summary&
/// 文件化XML序列化
/// &/summary&
/// &param name=&obj&&对象&/param&
/// &param name=&filename&&文件路径&/param&
public static void Save(object obj, string filename)
FileStream fs =
fs = new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
XmlSerializer serializer = new XmlSerializer(obj.GetType());
serializer.Serialize(fs, obj);
catch (Exception ex)
if (fs != null) fs.Close();
/// &summary&
/// 文件化XML反序列化
/// &/summary&
/// &param name=&type&&对象类型&/param&
/// &param name=&filename&&文件路径&/param&
public static object Load(Type type, string filename)
FileStream fs =
fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
XmlSerializer serializer = new XmlSerializer(type);
return serializer.Deserialize(fs);
catch (Exception ex)
if (fs != null) fs.Close();
/// &summary&
/// 文本化XML序列化
/// &/summary&
/// &param name=&item&&对象&/param&
public string ToXml&T&(T item)
XmlSerializer serializer = new XmlSerializer(item.GetType());
StringBuilder sb = new StringBuilder();
using (XmlWriter writer = XmlWriter.Create(sb))
serializer.Serialize(writer, item);
return sb.ToString();
/// &summary&
/// 文本化XML反序列化
/// &/summary&
/// &param name=&str&&字符串序列&/param&
public T FromXml&T&(string str)
XmlSerializer serializer = new XmlSerializer(typeof(T));
using (XmlReader reader = new XmlTextReader(new StringReader(str)))
return (T)serializer.Deserialize(reader);
#endregion
#region SoapFormatter序列化
/// &summary&
/// SoapFormatter序列化
/// &/summary&
/// &param name=&item&&对象&/param&
public static string ToSoap&T&(T item)
SoapFormatter formatter = new SoapFormatter();
using (MemoryStream ms = new MemoryStream())
formatter.Serialize(ms, item);
ms.Position = 0;
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(ms);
return xmlDoc.InnerX
/// &summary&
/// SoapFormatter反序列化
/// &/summary&
/// &param name=&str&&字符串序列&/param&
public static T FromSoap&T&(string str)
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(str);
SoapFormatter formatter = new SoapFormatter();
using (MemoryStream ms = new MemoryStream())
xmlDoc.Save(ms);
ms.Position = 0;
return (T)formatter.Deserialize(ms);
#endregion
#region BinaryFormatter序列化
/// &summary&
/// BinaryFormatter序列化
/// &/summary&
/// &param name=&item&&对象&/param&
public static string ToBinary&T&(T item)
BinaryFormatter formatter = new BinaryFormatter();
using (MemoryStream ms = new MemoryStream())
formatter.Serialize(ms, item);
ms.Position = 0;
byte[] bytes = ms.ToArray();
StringBuilder sb = new StringBuilder();
foreach (byte bt in bytes)
sb.Append(string.Format(&{0:X2}&, bt));
return sb.ToString();
/// &summary&
/// BinaryFormatter反序列化
/// &/summary&
/// &param name=&str&&字符串序列&/param&
public static T FromBinary&T&(string str)
int intLen = str.Length / 2;
byte[] bytes = new byte[intLen];
for (int i = 0; i & intL i++)
int ibyte = Convert.ToInt32(str.Substring(i * 2, 2), 16);
bytes[i] = (byte)
BinaryFormatter formatter = new BinaryFormatter();
using (MemoryStream ms = new MemoryStream(bytes))
return (T)formatter.Deserialize(ms);
#endregion
/// &summary&
/// 将对象序列化为二进制字节
/// &/summary&
/// &param name=&obj&&待序列化的对象&/param&
/// &returns&&/returns&
public static byte[] SerializeToBinary(object obj)
byte[] bytes = new byte[2500];
using (MemoryStream memoryStream = new MemoryStream())
BinaryFormatter bformatter = new BinaryFormatter();
bformatter.Serialize(memoryStream, obj);
memoryStream.Seek(0, 0);
if (memoryStream.Length & bytes.Length)
bytes = new byte[memoryStream.Length];
bytes = memoryStream.ToArray();
/// &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);
/// &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&
/// 从二进制文件中反序列化为对象
/// &/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);
/// &summary&
/// 获取对象的转换为二进制的字节大小
/// &/summary&
/// &param name=&obj&&&/param&
/// &returns&&/returns&
public static long GetByteSize(object obj)
BinaryFormatter bFormatter = new BinaryFormatter();
using (MemoryStream stream = new MemoryStream())
bFormatter.Serialize(stream, obj);
result = stream.L
/// &summary&
/// 克隆一个对象
/// &/summary&
/// &param name=&obj&&待克隆的对象&/param&
/// &returns&克隆的一个新的对象&/returns&
public static object Clone(object obj)
object cloned =
BinaryFormatter bFormatter = new BinaryFormatter();
using (MemoryStream memoryStream = new MemoryStream())
bFormatter.Serialize(memoryStream, obj);
memoryStream.Seek(0, SeekOrigin.Begin);
cloned = bFormatter.Deserialize(memoryStream);
catch //(Exception e)
/// &summary&
/// 从文件中读取文本内容
/// &/summary&
/// &param name=&path&&文件路径&/param&
/// &returns&文件的内容&/returns&
public static string ReadFile(string path)
string content = string.E
using (StreamReader reader = new StreamReader(path))
content = reader.ReadToEnd();
public static byte[] Serialize(object value, out SerializedType type, uint compressionThreshold)
if (value is byte[])
bytes = (byte[])
type = SerializedType.ByteA
if (bytes.Length & compressionThreshold)
bytes = compress(bytes);
type = pressedByteA
else if (value is string)
bytes = Encoding.UTF8.GetBytes((string)value);
type = SerializedType.S
if (bytes.Length & compressionThreshold)
bytes = compress(bytes);
type = pressedS
else if (value is DateTime)
bytes = BitConverter.GetBytes(((DateTime)value).Ticks);
type = SerializedType.D
else if (value is bool)
bytes = new byte[] { (byte)((bool)value ? 1 : 0) };
type = SerializedType.B
else if (value is byte)
bytes = new byte[] { (byte)value };
type = SerializedType.B
else if (value is short)
bytes = BitConverter.GetBytes((short)value);
type = SerializedType.S
else if (value is ushort)
bytes = BitConverter.GetBytes((ushort)value);
type = SerializedType.US
else if (value is int)
bytes = BitConverter.GetBytes((int)value);
type = SerializedType.I
else if (value is uint)
bytes = BitConverter.GetBytes((uint)value);
type = SerializedType.UI
else if (value is long)
bytes = BitConverter.GetBytes((long)value);
type = SerializedType.L
else if (value is ulong)
bytes = BitConverter.GetBytes((ulong)value);
type = SerializedType.UL
else if (value is float)
bytes = BitConverter.GetBytes((float)value);
type = SerializedType.F
else if (value is double)
bytes = BitConverter.GetBytes((double)value);
type = SerializedType.D
using (MemoryStream ms = new MemoryStream())
new BinaryFormatter().Serialize(ms, value);
bytes = ms.GetBuffer();
type = SerializedType.O
if (bytes.Length & compressionThreshold)
bytes = compress(bytes);
type = pressedO
private static byte[] compress(byte[] bytes)
using (MemoryStream ms = new MemoryStream())
using (DeflateStream gzs = new DeflateStream(ms, press, false))
gzs.Write(bytes, 0, bytes.Length);
ms.Close();
return ms.GetBuffer();
private static byte[] decompress(byte[] bytes)
using (MemoryStream ms = new MemoryStream(bytes, false))
using (DeflateStream gzs = new DeflateStream(ms, CompressionMode.Decompress, false))
using (MemoryStream dest = new MemoryStream())
byte[] tmp = new byte[bytes.Length];
while ((read = gzs.Read(tmp, 0, tmp.Length)) != 0)
dest.Write(tmp, 0, read);
dest.Close();
return dest.GetBuffer();
public static object DeSerialize(byte[] bytes, SerializedType type)
switch (type)
case SerializedType.String:
return Encoding.UTF8.GetString(bytes);
case SerializedType.Datetime:
return new DateTime(BitConverter.ToInt64(bytes, 0));
case SerializedType.Bool:
return bytes[0] == 1;
case SerializedType.Byte:
return bytes[0];
case SerializedType.Short:
return BitConverter.ToInt16(bytes, 0);
case SerializedType.UShort:
return BitConverter.ToUInt16(bytes, 0);
case SerializedType.Int:
return BitConverter.ToInt32(bytes, 0);
case SerializedType.UInt:
return BitConverter.ToUInt32(bytes, 0);
case SerializedType.Long:
return BitConverter.ToInt64(bytes, 0);
case SerializedType.ULong:
return BitConverter.ToUInt64(bytes, 0);
case SerializedType.Float:
return BitConverter.ToSingle(bytes, 0);
case SerializedType.Double:
return BitConverter.ToDouble(bytes, 0);
case SerializedType.Object:
using (MemoryStream ms = new MemoryStream(bytes))
return new BinaryFormatter().Deserialize(ms);
pressedByteArray:
return DeSerialize(decompress(bytes), SerializedType.ByteArray);
pressedString:
return DeSerialize(decompress(bytes), SerializedType.String);
pressedObject:
return DeSerialize(decompress(bytes), SerializedType.Object);
case SerializedType.ByteArray:
您可能的代码
相关聚客文章
相关专栏文章

我要回帖

更多关于 c 序列化和反序列化 的文章

 

随机推荐