0

I would like to convert all class property names and values to a Dictionary<string, string>. However instead of using the regular property names I would like the JsonPropertyNames i.e.

dictionary.Add(item.JsonPropertyName, item.Value)

Something like the answer but modified to get the JsonPropertyNames. Getting these attributes in a loop similar to below is proving more difficult than expected.

https://stackoverflow.com/a/9210587/4280872

Location local = new Location();
local.city = "Lisbon";
local.country = "Portugal";
local.state = "None";

PropertyInfo[] infos = local.GetType().GetProperties();

Dictionary<string,string> dix = new Dictionary<string,string> ();

foreach (PropertyInfo info in infos)
{
    dix.Add(info.Name, info.GetValue(local, null).ToString());
}

foreach (string key in dix.Keys)
{
    Console.WriteLine("nameProperty: {0}; value: {1}", key, dix[key]);
}

Console.Read();
AdVic
  • 87
  • 1
  • 2
  • 6
  • 1
    _"I would like to convert all class property names and values to a `Dictionary`"_ - what if the object has a non-`String` property? Or is part of an object-graph? – Dai Jul 19 '22 at 05:15
  • Thanks @JeremyLakeman. Surprisingly google did not come up with such a quick result. I also did not have using.System.Reflection so couldn't access GetCustomAttribute method. However I was able to access GetCustomAttributes before adding the Reflection namespace which threw me off. – AdVic Jul 19 '22 at 06:09
  • Thanks @Dai. In my case I am able to call ToString safely on all the properties to get the intended result. It's a home project not a commercial one... Incidentally another way that almost worked was serializing the class then deserilizing to a Dictionary. Probably inefficient and ugly. Additionally System.Text converts eg "False" to bool on deserialization by default which wasn't desirable. – AdVic Jul 19 '22 at 09:59

0 Answers0