I have a class like following:
public class Client {
[JsonProperty("first_name")]
public string FirstName { get; set; }
[JsonProperty("last_name")]
public string LastName { get; set; }
}
using the following code I can get the properties and values in a dictionary of that class object:
var propertyValuesByName = client.GetType().GetProperties()
.Where(pi => pi.PropertyType == typeof(string))
.Select(pi => new { Val = (string) pi.GetValue(client), Name = pi.Name })
.ToDictionary(pi => pi.Name, pi => pi.Val);
so the dictionary contains property name as key and the property value as value. But what I want is, get the dictionary which key will be the object JsonProperty name instead of the real property name, means instead of "FirstName" I want "first_name" as key. How can I modify the above code to achieve this?
3
Answers
Use some more reflection to ger info from custom attribute:
Or :
Also note that if your object contains only string you can deserialize directly to
Dictionary<string, string>
.I guess it’s similar to the problem exposed in this thread :
How to get Json Property name using reflection in C#
If it’s not mandatory for you to access object using reflection, you can just deserialize a Json to a Dictionary<string,string> like this :
and then get the keys out of it using values.Keys.
Hope this helps
To get the property name of a JSON object in C#, you can use the nameof operator. For example, given the following JSON object:
You can use the nameof operator to get the property names like this:
Note that the nameof operator only works with compile-time constants, so it will not work with dynamically generated property names.
Alternatively, you can use the JsonPropertyAttribute to specify the property name in the JSON object. For example:
public class Person
you can then use reflection to get the property names like this:
var person = new Person { Name = "John Smith", Age = 30, City = "New York" };