I have a class like so:
[JsonObject(MemberSerialization.OptIn)]
public class foo
{
[JsonProperty("name_in_json")]
public string Bar { get; set; }
// etc.
public Dictionary<string, bool> ImageFlags { get; set; }
}
The JSON is generated from a CSV file originally, each line representing a foo object - it's basically flat, so I need to map certain keys to imageflags.
I tried to write a CustomCreationConverter based on the example here.
This seems to map the flags fine, but it fails setting normal properties - it looks for 'bar' instead of 'name_in_json'.
How would I go about getting 'name_in_json' value for an object of type foo?
edit:
current solution:
var custAttrs = objectType.GetProperties().Select(p => p.GetCustomAttributes(typeof(JsonPropertyAttribute), true)).ToArray();
var propNames = objectType.GetProperties().Select(p => p.Name.ToLower()).ToArray();
Dictionary<string, string> objProps = new Dictionary<string, string>();
for (int i = 0; i < propNames.Length; i++)
// not every property has json equivalent...
if (0 == custAttrs[i].Length)
{
continue;
}
var attr = custAttrs[i][0] as JsonPropertyAttribute;
objProps.Add(attr.PropertyName.ToLower(), propNames[i].ToLower());
}
This is an old post, but I would like to suggest a slight modification, which I think is cleaner. (Having recently faced the same problem) It uses anonymous types.
var pairs = objectType
.GetProperties()
.Select(p => new {
Property = p,
Attribute = p
.GetCustomAttributes(
typeof(JsonPropertyAttribute), true)
.Cast<JsonPropertyAttribute>()
.FirstOrDefault() });
var objProps = pairs
.Where(p => p.Attribute != null)
.ToDictionary(
p => p.Property.Name,
p => p.Attribute.PropertyName);
Okay, in the example above you get all property names from type with:
var objProps = objectType.GetProperties().Select(p => p.Name.ToLower()).ToArray();
So you use only actual property name, what youshould do instead is for each property get custom attribute of type JsonProperty
using GetCustomAttributes method, and get json property name from it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With