ASP.NET中把对象序列化成JSON字符串的三种方法

2022-05-09 12:04:14 浏览数 (1)

代码语言:javascript复制
                //方法1
                //using System.Runtime.Serialization.Json;
                //using System.IO;
                //using System.Text;
                //using System.Text.RegularExpressions;
                DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(arr.GetType());
                MemoryStream ms = new MemoryStream();
                jsonSerializer.WriteObject(ms, arr);
                String sRet = Encoding.UTF8.GetString(ms.ToArray());
                ms.Close();

                //将时间由"/Date(10000000000-0700)/" 格式转换成 "yyyy-MM-dd HH:mm:ss" 格式的字符串
                string sPattern = @"\/Date((d )-d )\/";
                MatchEvaluator myMatchEvaluator = new MatchEvaluator(m =>
                {
                    String sRet1 = "";
                    try
                    {
                        DateTime dt = DateTime.Parse(m.Groups[1].Value);
                        dt = dt.ToUniversalTime();
                        TimeSpan ts = dt - DateTime.Parse("1970-01-01");
                        sRet1 = string.Format("\/Date({0}-0700)\/", ts.TotalMilliseconds);
                    }
                    catch
                    { }
                    return sRet1;
                });
                Regex reg = new Regex(sPattern);
                sRet = reg.Replace(sRet, myMatchEvaluator);

                //方法二(第三方)
                //Newtonsoft.Json
                string sRet = Newtonsoft.Json.JsonConvert.SerializeObject(arr);
                
                //方法三
                //using System.Web.Script.Serialization;
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                string sRet = serializer.Serialize(arr);

0 人点赞