当前位置: 编程技术>.net/c#/asp.net
c#序列化和反序列化Json的方法
来源: 互联网 发布时间:2014-08-30
本文导语: c#进行序列化或反序列化时,需要添加引用: System.ServiceModel.Web 和 System.Runtime.Serialization,然后使用Using: 代码如下: using System.Runtime.Serialization.Json; using System.Runtime.Serialization; 1、序列化为字符串: 代码如下: public static st...
c#进行序列化或反序列化时,需要添加引用:
System.ServiceModel.Web 和 System.Runtime.Serialization,然后使用Using:
代码如下:
using System.Runtime.Serialization.Json;
using System.Runtime.Serialization;
using System.Runtime.Serialization;
1、序列化为字符串:
代码如下:
public static string SerializeToJsonString( object objectToSerialize )
{
using( MemoryStream ms = new MemoryStream() )
{
DataContractJsonSerializer serializer =
new DataContractJsonSerializer( objectToSerialize.GetType() );
serializer.WriteObject( ms, objectToSerialize );
ms.Position = 0;
using( StreamReader reader = new StreamReader( ms ) )
{
return reader.ReadToEnd();
}
}
}
{
using( MemoryStream ms = new MemoryStream() )
{
DataContractJsonSerializer serializer =
new DataContractJsonSerializer( objectToSerialize.GetType() );
serializer.WriteObject( ms, objectToSerialize );
ms.Position = 0;
using( StreamReader reader = new StreamReader( ms ) )
{
return reader.ReadToEnd();
}
}
}
2、反序列化:
代码如下:
public static T Deserialize( string jsonString )
{
using( MemoryStream ms = new MemoryStream( Encoding.Unicode.GetBytes( jsonString ) ) )
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer( typeof( T ) );
return ( T )serializer.ReadObject( ms );
}
}
{
using( MemoryStream ms = new MemoryStream( Encoding.Unicode.GetBytes( jsonString ) ) )
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer( typeof( T ) );
return ( T )serializer.ReadObject( ms );
}
}