How to deserialize JSON object with Newtonsoft when it's fields names are reserved keywords like "short"?
Asked Answered
C

2

5

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

I want to deserialize it like

Newtonsoft.Json.JsonConvert.DeserializeObject<SuggestionInfoDataOpf>(json_str);

but fields names should match.

Chopin answered 3/7, 2020 at 12:56 Comment(1)
name your field @short. or name it however you like, and use the JsonPropertyAttributeAthabaska
C
7

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

Causeway answered 3/7, 2020 at 12:57 Comment(0)
G
5

You should use keywords with @ like this:

class SuggestionInfoDataOpf
{
    public string code;
    public string full;
    public string @short;
    public string type;
}
Goal answered 3/7, 2020 at 12:58 Comment(1)
Thanks! Never knew that... ouch... what a shame.Icebreaker

© 2022 - 2024 — McMap. All rights reserved.