我正在编写一个读取JSON文件的工具.我正在使用NewtonSoft工具将JSOn反序列化为C#类.这是一个示例片段:
"name": "Fubar",
".NET version": "4.0",
"binding type": "HTTP",
Run Code Online (Sandbox Code Playgroud)
字段名称包含空格和C#标识符中无效的其他字符(.).这样做的正确方法是什么?
(不幸的是我没有更改JSON格式的选项.)
Cra*_* W. 18
使用该JsonProperty属性指示JSON中的名称.例如
[JsonProperty(PropertyName = "binding type")]
public string BindingType { get; set; }
Run Code Online (Sandbox Code Playgroud)
如果您使用的是System.Text.Json,则等效属性是JsonPropertyName:
[JsonPropertyName(".net version")]
public string DotNetVersion { get; set; }
Run Code Online (Sandbox Code Playgroud)
下面的例子:
public class Data
{
public string Name { get; set; }
[JsonPropertyName(".net version")]
public string DotNetVersion { get; set; }
[JsonPropertyName("binding type")]
public string BindingType { get; set; }
}
// to deserialize
var data = JsonSerializer.Deserialize<Data>(json);
Run Code Online (Sandbox Code Playgroud)