JsonHelper

csharp

浏览数:257

2019-1-8

 public static string ToJson(object obj)
   {
            string str = string.Empty;
            JavaScriptSerializer serializer = new JavaScriptSerializer();          
            str = serializer.Serialize(obj);
            //\/Date(-2209017600000)\/
            str = Regex.Replace(str, @"\\/Date\((-?\d+)\)\\/", match =>
            {
                DateTime dt = new DateTime(1970, 1, 1);
                dt = dt.AddMilliseconds(long.Parse(match.Groups[1].Value));
                dt = dt.ToLocalTime();
                return dt.ToString("yyyy-MM-dd HH:mm:ss");
            });           
            
            str = Regex.Replace(str, @"null", match =>
            {
               
                return "\"\"";
            });
           
            return str;
   }
   
   public static List<T> JsonToList<T>(string jsonStr)
   {
            List<T> jObject = null;
            try
            {
                JavaScriptSerializer serializer = new JavaScriptSerializer();  
                jObject = serializer.Deserialize<List<T>>(jsonStr);  
            }
            catch (Exception)
            {
                
                throw;
            }
            return jObject;
   }