public static void AddAttrFields <Attr>(this JObject jObject, object model, FieldToJTokenDelegate structHandler = null, FieldToJTokenDelegate classHandler = null) where Attr : Attribute { FieldHandlerDelegate preHandler = (object handleModel, FieldInfo fieldInfo, ref bool skip) => { Attr editorAttribute = fieldInfo.GetCustomAttribute(typeof(Attr)) as Attr; if (editorAttribute == null) { skip = true; } }; AddFields(jObject, model, preHandler, structHandler, classHandler); }
public static void AddFields(this JObject jObject, object model, FieldHandlerDelegate preHandler = null, FieldToJTokenDelegate structHandler = null, FieldToJTokenDelegate classHandler = null) { FieldInfo[] fields = model.GetType().GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); foreach (FieldInfo fieldInfo in fields) { bool preSkip = false; preHandler?.Invoke(model, fieldInfo, ref preSkip); if (preSkip) { continue; } object value = fieldInfo.GetValue(model); JToken jToken = null; if (value == null) { jToken = string.Empty; } else if (fieldInfo.FieldType.IsValueType && !fieldInfo.FieldType.IsEnum && !fieldInfo.FieldType.IsPrimitive) { // Struct if (structHandler != null) { JObject jField = null; structHandler.Invoke(model, fieldInfo, out jField); jToken = jField; } else { JObject jValue = new JObject(); AddFields(jValue, value); jToken = jValue; } } else if (fieldInfo.FieldType.IsClass && fieldInfo.FieldType != typeof(string)) { // Class if (classHandler != null) { JObject jField = null; classHandler.Invoke(model, fieldInfo, out jField); jToken = jField; } } else { jToken = value.ToString(); } if (jToken != null) { jObject.Add(fieldInfo.Name, jToken); } } }