C # traversing all attributes of an Object includes List generic nesting .,
My colleague encountered a problem: when using the mobile app interface, the returned data is in JSON format. The data attributes in json are of the string type, but NULL is not allowed, AH ). The Model has been created, and each attribute of the model is of the string type. The data layer uses EF. Some fields in the database can be empty. In this case, you need to verify whether the attribute is NULL and convert the attribute value to NULL "".
Solution: 1. traverse all attributes of the model. If it is NULL, the value is assigned "". 2. Nesting of the generic List <model> is supported.
Prerequisites: the model has only the following values: List <model>, string, and multi-layer nesting.
So I wrote the following code to traverse the attributes and encountered many problems: the first draft, temporary use, and subsequent improvements.
/// <Summary> /// if the model attribute is null, change null "".. This method is only used when all attributes are of the string type and is mainly used for mobile apps. Chj 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; // when the attribute contains parameters. If (obj! = Null) {foreach (var pi in typeArr) {// if (pi. propertyType = typeof (string) {if (pi. getValue (obj, null) = null) {pi. setValue (obj, "", null) ;}// when this attribute is List generic, or it is a reference type, array. Here it seems that there is a property that can be used to directly determine else if (pi. propertyType. isGenericType | pi. propertyType. isArray | pi. propertyType. isClass )//. getType () = typeof (Nullable) {var paras = pi. getIndexParameters (); // list of parameters of the indexed attribute 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 ;}
Recursion is used because multiple layers may be nested.
The temporary scheme is here, and will be improved occasionally...