编程语言
首页 > 编程语言> > C#把Object对象转换成JSON串

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;
 }

 

标签:obj,string,C#,Object,System,JSON,result,new,memoryStream
来源: https://www.cnblogs.com/xunmengrenli/p/15608412.html