我有一个API的JSON响应:
{
"arguments": {
"Configuration": {
"Building_Configuration.Parameters_SP.fixtureStrategy_SP": "ETA",
"Building_Configuration.Parameters_SP.dimensionSelection_SP": "Imperial",
"Building_Configuration.Parameters_SP.controllerRobotic_SP": false,
"Building_Configuration.Parameters_SP.controllerBACNet_SP": false
}
}
}我有一个Root.cs模型文件,我用JSON到C#转换器制作了这个文件,它与我在C# Visual 2019中的解决方案中的JSON相对应:
public class Root
{
public Arguments arguments { get; set; }
}
public class Arguments
{
public Configuration Configuration { get; set; }
}
public class Configuration
{
[JsonProperty("Building_Configuration.Parameters_SP.fixtureStrategy_SP")]
public string BuildingConfigurationParametersSPFixtureStrategySP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.dimensionSelection_SP")]
public string BuildingConfigurationParametersSPDimensionSelectionSP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.controllerRobotic_SP")]
public bool BuildingConfigurationParametersSPControllerRoboticSP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.controllerBACNet_SP")]
public bool BuildingConfigurationParametersSPControllerBACNetSP { get; set; }
}我试图以这种方式访问和返回BuildingConfigurationParametersSPFixtureStrategySP的值(上面的Configuration类中的第一个属性):
public string CreateExecPost()
{
/*...everthing here works fine down through the end of this method. I can set
breakpoints and step through the following code and look at the values of all the
following variables and all is well
....*/
var payload = new StringContent(newPost, Encoding.UTF8, "application/json");
var result = client.PostAsync(endpoint, payload).Result.Content.ReadAsStringAsync().Result;
Root MyObject = JsonConvert.DeserializeObject<Root>(result);
return MyObject.arguments.configuration.BuildingConfigurationParametersSPFixtureStrategySP;
} //The correct value for BuildingConfigurationParametersSPFixtureStrategySP is returned and all is well!所以,问题是为什么转换器会生成一个属性,比如.
[JsonProperty("Building_Configuration.Parameters_SP.fixtureStrategy_SP")]...above每个{ get; set; }语句?我已经研究和阅读了关于JsonProperty和JsonPropertyAttribute的内容,但我仍然不太清楚。我不知道这个工具用什么信号来生成属性,也不知道它为什么要这样做。
发布于 2022-06-26 06:36:25
默认情况下,这个工具用Json.net库生成代码,官方文档对这个类解释得不多:JsonProperty.htm
关于如何使用它,还有其他类似的问题,例如:JsonProperty在c#中的用途是什么?
这个类的一般用法是当您想要重命名一个属性时,或者需要重命名一个属性。最后一个是相关的。
json解析器通常尝试将属性名1:1与类属性匹配。但是,每当json属性名称包含保留关键字、语言语法或其他非法属性名称时,都需要将其重命名。
在您的示例中,名称Building_Configuration.Parameters_SP.fixtureStrategy_SP包含句点。如果尝试将get;set属性命名为这样,代码将不会编译。
生成代码的站点知道这一点,并将添加所需的JsonProperty来将完整的json属性名称映射到重命名为BuildingConfigurationParametersSPFixtureStrategySP的类字段(非法字符已被删除)。
查看有效的属性名称:https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/coding-style/identifier-names
供参考:使用其名称中的点访问属性
https://stackoverflow.com/questions/72758304
复制相似问题