我有一个像“A\/B”这样的 json 属性,我想在 C# 属性 AB 中反序列化它
我已经尝试过 System.Text.Json 和
[JsonPropertyName(@"A\/B")]
public bool AB { get; set; }
或者
[JsonProperty(@"A\/B")]
public bool AB { get; set; }
或者
[JsonProperty(PropertyName = (@"A\/B")]
public bool AB { get; set; }
或
[JsonPropertyName("A\\/B")]
public bool? AB { get; set; }
但未正确反序列化始终为 false,在 json 文件中为 true,如 "A/B": true,。
Json 示例:
{
"List": [
{
"Name": "name",
"A\/B": true,
},
{
"Name": "name1",
"A\/B": false,
}
]
}
任何建议都将受到高度赞赏。
最佳答案
如果 JSON 看起来像这样
{
"A\/B": true
}
那么属性的名称实际上只是 A/B
。
反斜杠字符还充当 JSON 语法中的转义字符,因此反斜杠实际上并不是属性名称的一部分。尽管在这种情况下正斜杠不需要任何转义,但转义它仍然是可以接受的。请参阅RFC 8259 section 7 .
因此,在您的 C# 代码中,您也不需要任何反斜杠:
[JsonProperty("A/B")]
或
[JsonPropertyName("A/B")]
取决于您使用的是 Json.NET 还是 System.Text.Json。
关于c# - 使用属性名称中的特殊字符反序列化 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75371314/