/// <summary>
/// 计算字符串的 MD5 哈希。若字符串为空,则返回空,否则返回计算结果。
/// </summary>
public static string ComputeMD5Hash( this string str )
{
string hash = str;
if ( str != null )
{
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
byte[] data = Encoding.ASCII.GetBytes( str );
data = md5.ComputeHash( data );
hash = "";
for ( int i = 0; i < data.Length; i++ )
hash += data[ i ].ToString( "x2" );
}
return hash;
}
/// <summary>
/// 获得 Json 描述的 .Net 对象
/// </summary>
public static T JsonToObject<T>( this string str )
{
return new JavaScriptSerializer().Deserialize<T>( str );
}
//object extensions
/// <summary>
/// 获得 obj 的 JSON 字符串
/// </summary>
public static string ToJson( this object obj )
{
return new JavaScriptSerializer().Serialize( obj );
}
//sample
public class Student
{
public string Name { get; set; }
public int Age { get; set; }
}
Student std = new Student() { Name = "xxxx", Age = 24 };
std.ToJson(); // => "\{ \"Name\": \"xxxx\", \"Age\": 24 \}"
string json = "\{ \"Name\": \"xxxx\", \"Age\": 24 \}";
Student s = json.JsonToObject<Student>();