c#进行序列化或反序列化时,需要添加引用:
System.ServiceModel.Web 和 System.Runtime.Serialization,然后使用Using:
复制代码 代码如下:
using System.Runtime.Serialization.Json;
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();
}
}
}
2、反序列化:
复制代码 代码如下:
public static T Deserialize<T>( string jsonString )
{
using( MemoryStream ms = new MemoryStream( Encoding.Unicode.GetBytes( jsonString ) ) )
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer( typeof( T ) );
return ( T )serializer.ReadObject( ms );
}
}