I need to change the values of the properties of a class in C# and I would like to have a generic method for it as it will be used for any class in my project.
Sample Classes (Entities):
public class Apple
{
public string Name {get;set;}
public string Value {get;set;}
public int ID {get; set;}
}
public class Seller
{
public Guid Id {get; set;}
public bool IsActive {get;set;}
}
Dummy Get & Serialize methods:
var newApple = GetApple(1);
Serializing into JSON String gives me:
{ "apple": { "id": 12345, "name": "Apple A", "value": "100" } }
var newSeller = GetSeller(new Guid());
Serializing into JSON String gives me:
{ "seller": { "id": 12345, "isActive": false } }
Expected JSON after encryption:
{"apple": { "id": "A##VSDDSVDGFDG!@12321",
"name": "SDD888#@##ASAS#40((!!AA", "value": "SSDSAD#$$$%^&#ADSAD)AA" }}
I want the JSON to be in the above format where I want to encrypt the property values alone and not the property name. I tried using dynamics in C# but the property names are not being set in dynamic.
My Generic Method:
private List<object> EncryptPropertiesAlone<T>(T newObject)
{
{
Type type = newObject.GetType();
PropertyInfo[] properties = type.GetProperties();
List<object> myObjectList = new List<object>();
foreach (PropertyInfo property in properties)
{
var encString = this.EncryptString(property.GetValue(newObject, null)?.ToString());
var propertName = property.Name;
dynamic MyDynamic = new System.Dynamic.ExpandoObject();
MyDynamic.propertName = encString;
myObjectList.Add(MyDynamic);
}
return myObjectList;
}
Any ideas how this can be achieved? If there is any built in method in DOTNET which can achieve this? Thanks in advance.