C# 把对象序列化 JSON 字符串 和把JSON字符串还原为对象

 /// <summary>
        /// 把对象序列化 JSON 字符串 
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="obj">对象实体</param>
        /// <returns>JSON字符串</returns>
        public static string GetJson<T>(T obj)
        {
            //记住 添加引用 System.ServiceModel.Web 
            /**
             * 如果不添加上面的引用,System.Runtime.Serialization.Json; Json是出不来的哦
             * */
            DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(T));
            using (MemoryStream ms = new MemoryStream())
            {
                json.WriteObject(ms, obj);
                string szJson = Encoding.UTF8.GetString(ms.ToArray());
                return szJson;
            }
        }
        /// <summary>
        /// 把JSON字符串还原为对象
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="szJson">JSON字符串</param>
        /// <returns>对象实体</returns>
        public static T ParseFormJson<T>(string szJson)
        {
            T obj = Activator.CreateInstance<T>();
            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(szJson)))
            {
                DataContractJsonSerializer dcj = new DataContractJsonSerializer(typeof(T));
                return (T)dcj.ReadObject(ms);
            }
        }

 //把一个单独的对象 转换为json字符串

                    StringBuilder sb = new StringBuilder();
                    sb.Append("{");
                    foreach (System.Reflection.PropertyInfo p in model.GetType().GetProperties())
                    {
                        var ss = p.Name; //属性名称
                        if (ss== "Role"|| ss == "Department" || ss == "ApplySolver")
                        {
                            continue;
                        }
                        var s1 = p.GetValue(model);//属性值
                        sb.AppendFormat("\"{0}\":\"{1}\"", ss,s1);
                        sb.Append(",");
                    }
                    sb.Remove(sb.Length - 1, 1);
                    sb.Append("}");
                    desc = sb.ToString();
                    sb.Length = 0;

 

posted @ 2018-07-02 12:04  enych  阅读(260)  评论(0编辑  收藏  举报