Reputation: 146910
I've got a DTO which is serialized to JSON. I need to know the name of the property as it will appear in the JSON. I have the appropriate IContractResolver
, but I'm not sure how to go from this to the final property name.
I've used GetResolvedPropertyName
, which is a start but not an end. For example, since it takes a string as argument it can't look up e.g. JsonPropertyAttribute
on the property. There may be other cases where it doesn't do the complete job.
How can I get the final property name, given that I have the PropertyInfo
and the ContractResolver
?
Upvotes: 3
Views: 350
Reputation: 129687
I'm not sure I understand why you'd need to do this, but, assuming your IContractResolver
derives from the DefaultContractResolver
, you can get the property names like this:
JsonObjectContract contract = (JsonObjectContract)resolver.ResolveContract(typeof(DTO));
var dict = contract.Properties.ToDictionary(p => p.UnderlyingName, p => p.PropertyName);
Console.WriteLine("Serialized property names will be: ");
foreach (var kvp in dict)
{
Console.WriteLine(kvp.Key + " => " + kvp.Value);
}
Fiddle: https://dotnetfiddle.net/RnwnRc
Upvotes: 2