第一种 引用System.Web.Script.Serialization.dll
public string JsonAndObj(Object obj) { JavaScriptSerializer js = new JavaScriptSerializer(); string myJson = js.Serialize(obj); return myJson; }
第二种 引用System.IO 和 System.Runtime.Serialization.Json.dll
public string Obj2String(object obj) { string result; try { using (MemoryStream memoryStream = new MemoryStream()) { new DataContractJsonSerializer(obj.GetType()).WriteObject(memoryStream, obj); result = Encoding.UTF8.GetString(memoryStream.ToArray()); } } catch (Exception ex) { //DebugType dt = DebugType.err; //string msg = string.Format("对象JSON序列化失败,错误信息为{0}", ex.Message); //DebugEventArgs e = new DebugEventArgs(dt, msg); //Debug.OnRetrunDebug(e); result = ""; } return result; }