Setting properties of individual objects based on a list of object properties

I have an intermediate object between my Entity Framework objects and a JSON object that I serialize / deserialize to import and export to a text file.

When I export from an entity structure, I use the following code to repeat the properties of entity types ... If the property in the object matches the property from the enumeration that I have, the property is stored in the JSON object, This stops the entity of specific properties from cluttering my JSON.

var blockProperties = typeof(FixedLengthBlock).GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (var property in blockProperties) { if (Enum.GetNames(typeof(ModuleSettingEnum)).Contains(property.Name.ToLower()) && property.GetValue((FixedLengthBlock)element, null) != null) blockJsonEntity.Properties.Add(property.Name, property.GetValue((FixedLengthBlock)element, null).ToString()); } 

While the above code works, I can't think of the same way to do the opposite. When reading from JSON, I have properties / values ​​in the dictionary. I know that I can run EF Entity properties and look for a dictionary if it contains such a key:

 var blockProperties = typeof(FixedLengthBlock).GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (var property in blockProperties) { if (block.Properties.ContainsKey(property.Name)) { ???????What goes here?????? } } 

How to get a mapped property into a newly created object that I made to get information. I would really like to avoid the big switch statement.

My Json object is as follows:

 public class JsonEntity { public string Name { get; set; } public string Type { get; set; } public Dictionary<string, string> Properties { get; set; } public List<JsonEntity> SubEntities { get; set; } public JsonEntity() { Properties = new Dictionary<string, string>(); } } 
+4
source share
1 answer

Ok, so if we deserialize to the same type, try this:

 var bindingFlags = BindingFlags.Public | BindingFlags.Instance; var blockProperties = typeof(FixedLengthBlock).GetProperties(bindingFlags); var newObj = Activator.CreateInstance(typeof(FixedLengthBlock)) foreach (var property in blockProperties) { if (block.Properties.ContainsKey(property.Name)) { var propertyInfo = newObj.GetType().GetProperty(property.Name, bindingFlags); if (propertyInfo == null) { continue; } propertyInfo.SetValue(newObj, block.Properties[property.Name]); } } 
+2
source

Source: https://habr.com/ru/post/1441354/


All Articles