. NET 3.5 also contains a newNew System. Runtime. Serialization. DataContractJsonSerializer classClass, you can also use itJSON (JavaScript Object Notation)Serialization/deserialization.
/// <Summary>
/// Json data conversion Encapsulation
/// </Summary>
Public static class JsonHelper
{
/// <Summary>
/// Convert the time format from "\/Date (10000000000-0700) \/" to a string in the format of "yyyy-MM-dd HH: mm: ss"
/// </Summary>
/// <Param name = "m"> </param>
/// <Returns> </returns>
Private static string GetDatetimeString (Match m)
{
String sRet = "";
Try
{
System. DateTime dt = new DateTime (1970, 1, 1 );
Dt = dt. AddMilliseconds (long. Parse (m. Groups [1]. Value ));
Dt = dt. ToLocalTime ();
SRet = dt. ToString ("yyyy-MM-dd HH: mm: ss ");
}
Catch
{}
Return sRet;
}
/// <Summary>
/// Convert the time string in the format of "yyyy-MM-dd HH: mm: ss" to "\/Date (10000000000-0700) \/"
/// </Summary>
/// <Param name = "m"> </param>
/// <Returns> </returns>
Private static string GetDatetimeJson (Match m)
{
String sRet = "";
Try
{
DateTime dt = DateTime. Parse (m. Groups [1]. Value );
Dt = dt. ToUniversalTime ();
TimeSpan ts = dt-DateTime. Parse ("1970-01-01 ");
SRet = string. Format ("\/Date ({0}-0700) \/", ts. TotalMilliseconds );
}
Catch
{}
Return sRet;
}
/// <Summary>
/// Extended Object method ToJson
/// </Summary>
/// <Param name = "obj"> </param>
/// <Returns> </returns>
Public static String ToJson (this object obj)
{
DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer (obj. GetType ());
MemoryStream MS = new MemoryStream ();
JsonSerializer. WriteObject (MS, obj );
String sRet = Encoding. UTF8.GetString (ms. ToArray ());
Ms. Close ();
// Convert the time format from "\/Date (10000000000-0700) \/" to a string in the format of "yyyy-MM-dd HH: mm: ss"
String sPattern = @ "\/Date \ (\ d +)-\ d + \)\\/";
MatchEvaluator myMatchEvaluator = new MatchEvaluator (GetDatetimeString );
Regex reg = new Regex (sPattern );
SRet = reg. Replace (sRet, myMatchEvaluator );
Return sRet;
}
/// <Summary>
/// Jason deSerialize
/// </Summary>
/// <Typeparam name = "T"> </typeparam>
/// <Param name = "sJason"> </param>
/// <Returns> </returns>
Public static T FromJson <T> (String sJasonData)
{
// Convert the time string in the format of "yyyy-MM-dd HH: mm: ss" to "\/Date (10000000000-0700) \/"
String sPattern = @ "(\ d {4}-\ d {2}-\ d {2} \ s \ d {2 }:\ d {2 }: \ d {2 })";
MatchEvaluator myMatchEvaluator = new MatchEvaluator (GetDatetimeJson );
Regex reg = new Regex (sPattern );
String src = reg. Replace (sJasonData, myMatchEvaluator );
DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer (typeof (T ));
MemoryStream MS = new MemoryStream (Encoding. UTF8.GetBytes (src ));
Object obj = jsonSerializer. ReadObject (MS );
Return (T) obj;
}
}
From: http://hi.baidu.com/woxxf/blog/item/66edcf51447d382343a75b5d.html