Esa
Esa

Reputation: 1131

How do I get the name of a JsonProperty in JSON.Net?

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());
 }

Upvotes: 13

Views: 15192

Answers (2)

Thierry Prost
Thierry Prost

Reputation: 1025

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);

Upvotes: 8

Pavel Krymets
Pavel Krymets

Reputation: 6293

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.

Upvotes: 5

Related Questions