C#把Object对象转换成JSON串

第一种 引用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;
 }

 

上一篇:抽象工厂模式


下一篇:mySQL 常用增删改查