Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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());
 }
like image 471
Esa Avatar asked Jun 12 '12 06:06

Esa


2 Answers

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);
like image 158
Thierry Prost Avatar answered Sep 19 '22 11:09

Thierry Prost


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.

like image 32
Pavel Krymets Avatar answered Sep 20 '22 11:09

Pavel Krymets