How to deserialize JSON object with Newtonsoft when it's fields names are reserved keywords like "short"?
I have some JSON object:
"opf": { "type": "2014", "code": "12247", "full": "Публичное акционерное общество", "short": "ПАО" }
I want it to deserialize it into my class:
class SuggestionInfoDataOpf { public string code; public string full; public string short; //ERROR. Of course I can't declare this field public string type; }
What to do?.. I want to deserialize it like that: Newtonsoft.Json.JsonConvert.DeserializeObject<SuggestionInfoDataOpf>(json_str);
, but fields names should match.
By using the JsonProperty
attribute
class SuggestionInfoDataOpf { [JsonProperty("short")] public string Something {get; set;} }
Or using the prefix "@" before the name of the property. Using it you can name a member the same as a keyword
class SuggestionInfoDataOpf { public string @short; }
But IMO the JsonProperty
is better, as it allows you to keep to the C# naming guidelines as well as visually separating members from keywords
You should use keywords with @
like this:
class SuggestionInfoDataOpf { public string code; public string full; public string @short; public string type; }