Json 轉 指定 C#對象,給c#對象賦值

先引用
Newtonsoft.Json.dll

//然後
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;

方法如下

支持主表子表一起通過post發過來,逐個解析

        /// <summary>
        /// 通過POST返回對象
        /// </summary>
        /// <param name="obj">傳入要賦值的對象</param>
        /// <param name="getjson">傳入json字符串(解密的即可)</param>
        /// <returns></returns>
        public static object GetPostObj(object obj,  string getjson)
        {
            try
            {
                if (getjson.IndexOf("[") < 0)
                {
                    getjson = "[" + getjson + "]";
                }
                //序列化成對象
                JArray ja = (JArray)JsonConvert.DeserializeObject(getjson);
                //ja[0]["keys"].ToString()
                //產生一個有值的對象 obj.GetType().GetProperties()獲取所有屬性
                foreach (System.Reflection.PropertyInfo p in obj.GetType().GetProperties())
                {

                    var property = obj.GetType().GetProperty(p.Name);//獲取字段的類型
                    var str = ja[0][p.Name];
                    if (str != null)//如果有此屬性就賦值
                    {
                        //通過反射將屬性賦值
                        if (!property.PropertyType.IsGenericType)
                        {
                            //非泛型
                            property.SetValue(obj, string.IsNullOrEmpty(ja[0][p.Name].ToString()) ? null : Convert.ChangeType(ja[0][p.Name].ToString(), property.PropertyType), null);
                        }
                        else
                        {
                            //泛型Nullable<>
                            Type genericTypeDefinition = property.PropertyType.GetGenericTypeDefinition();
                            if (genericTypeDefinition == typeof(Nullable<>))
                            {
                                property.SetValue(obj, string.IsNullOrEmpty(ja[0][p.Name].ToString()) ? null : Convert.ChangeType(ja[0][p.Name].ToString(), Nullable.GetUnderlyingType(property.PropertyType)), null);
                            }
                        }
                        str = null;
                    }
                    str = null;
                }
                return obj; //將賦值好的對象返回
            }
            catch (Exception ex)
            { throw ex; }
        }

        /// <summary>
        /// 獲取POST的字符串
        /// </summary>
        /// <param name="context">HttpContext 對象</param>
        /// <returns>返回解密字符串</returns>
        public static string GetPostStr(HttpContext context)
        {
            System.IO.Stream s = context.Request.InputStream;//獲取POST的字符串
            int count = 0;
            byte[] buffer = new byte[1024];
            System.Text.StringBuilder builder = new System.Text.StringBuilder();
            while ((count = s.Read(buffer, 0, 1024)) > 0)
            {
                builder.Append(System.Text.Encoding.UTF8.GetString(buffer, 0, count));
            }
            s.Flush();
            s.Close();
            s.Dispose();
           string getjson = HttpUtility.UrlDecode(builder.ToString());
           return getjson;
        }

使用方法:

Model.WT_GPJL obj = new Model.WT_GPJL(); //創建XXX對象(數據庫中主表)
Model.WT_GPJLS objs = new Model.WT_GPJLS();//創建XXX對象(數據庫中子表)
string str = GetPostStr(context);// 傳入HttpContext 獲取post的字符串
obj = GetPostObj(obj, str) as Mes.Model.WT_GPJL; //給主表對象賦值
objs = GetPostObj(objs, str) as Mes.Model.WT_GPJLS; //給子表對象賦值
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章