I'm digging into an object which contains "values" in a string format that correspond to objects and properties nested within the object I get said values from. I.E. If my object contains a list of nested objects that contains, say.. Name, within a Contact object, then I have a "value" that might read something like "ContactInfo[0].Name".
How do I verify the property exists? I'm pretty sure that if I can figure this first part out, then I can worry about getting the value with a lot less difficulty.
I've tried using something along the lines of:
public static bool HasProperty(this object obj, string propertyName)
{
return obj.GetType().GetProperty(propertyName) != null;
}
with the arguments "MasterInfo", "Keys[0].KeyWord" and "Keys[1].Keyword" respectively.
I've tried breaking them down by DOT notation into segements and everything else I can think of, but I can't seem to use the keywords in the method successfully. Always False.
I tried running the MasterInfo object through a routine that broke the keyword down by '.' and iterated over each portion, but no change in the result... always False.
Fresh eyes are so very welcome! I've got to be missing something simple and/or right in front of me...
// simplified object example
public class MasterInfo
{
public int Id { get; set; }
public List<ContactInfo> Contacts {get; set;}
public Message MessageDetail { get; set; }
public List<Key> Keys { get; set; }
}
public class ContactInfo
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
}
public class Message
{
public int Id { get; set; }
public string MessageContent { get; set; }
}
public class Key
{
public int Id { get; set; }
public string KeyWord { get; set; }
}
// serialized JSON of what the MasterInfo class would be populated with, easier to read than with '.' notation
{
"Id" : 1,
"Contacts" : [
{
"Id" : 1,
"Name" : "Beavis",
"Email" : "beavis@asd.asd"
}
],
"MessageDetail" : {
"Id" : 23,
"MessageContent" : "Hello, %%Contacts[0].Name%%, this was sent to you at %%Contacts[0].Email%%"
},
"Keys" : [
{
"Id" : 1,
"KeyWord" : "Contacts[0].Name"
},
{
"Id" : 2,
"KeyWord" : "Contacts[0].Email"
}
]
}
// method I'm trying to use to verify the keyword (property) exists before attempting to get it's value...
public static bool HasProperty(this object obj, string propertyName)
{
return obj.GetType().GetProperty(propertyName) != null;
}
So far, everything turns up false when evaluated. I'm pretty sure this has to do with the fact that I'm diving into nested objects, but at this point I'm not certain of anything.