Kos*_*mos 3 .net c# reserved-words json.net json-deserialization
我有一些 JSON 对象:
"opf": {
"type": "2014",
"code": "12247",
"full": "????????? ??????????? ????????",
"short": "???"
}
Run Code Online (Sandbox Code Playgroud)
我希望它将它反序列化到我的班级中:
class SuggestionInfoDataOpf
{
public string code;
public string full;
public string short; //ERROR. Of course I can't declare this field
public string type;
}
Run Code Online (Sandbox Code Playgroud)
怎么办?.. 我想像这样反序列化它:Newtonsoft.Json.JsonConvert.DeserializeObject<SuggestionInfoDataOpf>(json_str);,但字段名称应该匹配。
通过使用JsonProperty属性
class SuggestionInfoDataOpf
{
[JsonProperty("short")]
public string Something {get; set;}
}
Run Code Online (Sandbox Code Playgroud)
或者在属性名称前使用前缀“@”。使用它,您可以将成员命名为与关键字相同的名称
class SuggestionInfoDataOpf
{
public string @short;
}
Run Code Online (Sandbox Code Playgroud)
但是 IMOJsonProperty更好,因为它允许您遵守 C# 命名指南以及在视觉上将成员与关键字分开
您应该使用@这样的关键字:
class SuggestionInfoDataOpf
{
public string code;
public string full;
public string @short;
public string type;
}
Run Code Online (Sandbox Code Playgroud)