How to get JsonProperty name in JSON.Net?

I have a class like:

[JsonObject(MemberSerialization.OptIn)] public class foo { [JsonProperty("name_in_json")] public string Bar { get; set; } // etc. public Dictionary<string, bool> ImageFlags { get; set; } } 

JSON is generated from the CSV file initially, each line represents a foo object - it is mostly flat, so I need to map specific keys to image flags.

I tried to write CustomCreationConverter using an example here .

It looks like the flags are fine, but the usual properties cannot be set - it searches for "bar" instead of "name_in_json".

How do I get the value 'name_in_json' 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()); } 
+6
source share
1 answer

Well, in the above example, you will get all property names from the type:

 var objProps = objectType.GetProperties().Select(p => p.Name.ToLower()).ToArray(); 

Thus, you only use the actual name of the property, what you should do instead, for each property, gets a custom attribute of type JsonProperty using the GetCustomAttributes method, and get the json property name from it.

+3
source

Source: https://habr.com/ru/post/917850/


All Articles