/// <summary> /// 将对象序列化为JSON格式 /// </summary> /// <param name="o">对象</param> /// <returns>json字符串</returns> public static string SerializeObject(object o) { string json = JsonConvert.SerializeObject(o); return json; }
/// <summary> /// 解析JSON字符串生成对象实体 /// </summary> /// <typeparam name="T">对象类型</typeparam> /// <param name="json">json字符串(eg.{"ID":"112","Name":"石子儿"})</param> /// <returns>对象实体</returns> public static T DeserializeJsonToObject<T>(string json) where T : class { JsonSerializer serializer = new JsonSerializer(); StringReader sr = new StringReader(json); object o = serializer.Deserialize(new JsonTextReader(sr), typeof(T)); T t = o as T; return t; }
调用:
List<Model.BAS.T_BAS_ContractVisit> visitList = T_BAS_ContractVisitBll.Instance.GetModelList(strSql); T_BAS_TabDataLog log = new T_BAS_TabDataLog() { ID = Convert.ToInt32(contractIds[k]), TabName = "T_BAS_ContractVisit", //Content = JsonHelper.SerializeDatatable(visitList.Tables[0]), Content = JsonHelper.SerializeObject(visitList), ActionName = sysUser.DisplayName, ActionTime = DateTime.Now, ActionType = "授权", ActionUser = sysUser.LoginName };
if (!string.IsNullOrEmpty(log.Content)&&log.Content.Length > 10) { List<Model.BAS.T_BAS_ContractVisit> list = HX.Common.JsonHelper.DeserializeJsonToObject<List<Model.BAS.T_BAS_ContractVisit>>(log.Content); if (list.Count > 0) { foreach (var item in list) { if (item.VisitType == 1) { userNames += item.VisitDisplay + ","; } else { deptNames += item.VisitDisplay + ","; } } } }