同事遇到一個問題:在做手機app接口時,返回JSON格式,json里面的數據屬性均是string類型,但不能出現NULL(手機端那邊說處理很麻煩,哎)。Model已經創建好了,而且model的每個屬性均是string類型。數據層使用EF。數據庫也有些字段可為空。這時,需要大量的驗證屬性是否為NULL,並將屬性值為NULL的轉換成"".
解決方案:1遍歷model各個屬性,當為NULL時,賦值"".2.支持泛型List<model>的嵌套。
前提條件:model的值只有這幾種,List<model> ,string ,多層嵌套。
於是寫了如下代碼遍歷屬性,遇到很多問題,初稿,臨時用,后面完善。
/// <summary> /// 去除model屬性為null 的情況,把null改成""。。該方法僅用在屬性均為string類型的情況,主要用於手機APP。 chj 2015-5-7 17:39:21 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="inputModel"></param> /// <returns></returns> public static object CJRemoveNULLByRecursive(object obj) { Type t = obj.GetType(); var typeArr = t.GetProperties(); object tempItem;//應對屬性含有參數時。 if (obj != null ) { foreach (var pi in typeArr) { //當屬性為字符串時 if (pi.PropertyType == typeof(string)) { if (pi.GetValue(obj, null)==null) { pi.SetValue(obj, "", null); } } //當該屬性為List泛型時,或者為引用類型,數組時。這里好像有個屬性可以直接判斷 else if(pi.PropertyType.IsGenericType||pi.PropertyType.IsArray||pi.PropertyType.IsClass)//.GetType()=typeof(Nullable)) { var paras= pi.GetIndexParameters(); //索引化屬性的參數列表 if (paras.Count()> 0) { int i = 0; tempItem = pi.GetValue(obj, new object[] { 0 }); while (tempItem!=null) { pi.SetValue(obj, CJRemoveNULLByRecursive(tempItem), new object[] { i }); i++; try { tempItem = pi.GetValue(obj, new object[] { i }); } catch (Exception) { break; } } } else { pi.SetValue(obj, CJRemoveNULLByRecursive(pi.GetValue(obj, null)), null); } } } } else { return ""; } return obj; }
由於可能嵌套多層,使用遞歸。
臨時方案,留在這,后面不定期完善中。。。