AJax編程經常需要Object<=>JSON之間轉換,寫了二個擴展方法:
public static string ToJSON(this object obj)
public static T ParseJSON<T>(this string str)
public static class JSONExtension
{
public static string ToJSON(this object obj)
{
DataContractJsonSerializer serializer = new DataContractJSonSerializer(obj.GetType());
using (MemoryStream ms = new MemoryStream())
{
serializer.WriteObject(ms, obj);
return Encoding.Default.GetString(ms.ToArray());
}
}
public static T ParseJSON<T>(this string str)
{
T obj = Activator.CreateInstance<T>();
using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(str)))
{
DataContractJsonSerializer serializer = new DataContractJSonSerializer(obj.GetType());
return (T)serializer.ReadObject(ms);
}
}
}