我需要反序列化一个json,该json的属性名称之间带有一个“空格”。(“关联团队”和“联系点”)。我已经尝试通过创建强类型对象来反序列化json字符串,但是它无法映射这2个属性。
JSON字符串:(jsonString)
{
"id": "/subscriptions/911yyy-1234-4695-a90f-943xxxxxxx/resourceGroups/sample",
"name": "sample",
"type": null,
"properties": {
"provisioningState": "Succeeded"
},
"location": "westus",
"tags": {
"Associated Team": "Sample Team",
"Description": "Resource Group for Azure",
"Point of Contact": "abc@xyz.com"
}
}
.Net代码段:
var deserializedResourceGroupDetails = JsonConvert.DeserializeObject<AzureResourceData>(jsonString);
AzurResourceData.cs类:
public class Tags
{
[JsonProperty("associatedTeam")]
public string associatedTeam { get; set; }
public string description { get; set; }
[JsonProperty("pointOfContact")]
public string pointOfContact { get; set; }
}
public class Properties
{
public string provisioningState { get; set; }
}
public class AzureResourceData
{
public string id { get; set; }
public string name { get; set; }
public string location { get; set; }
public Tags tags { get; set; }
public Properties properties { get; set; }
}
我还尝试过动态地对json进行反序列化(如下),但是由于两个属性之间的名称之间有空格,因此我又无法获取这两个属性的值。
dynamic deserializedResourceGroupDetails = JsonConvert.DeserializeObject(jsonString)));
答案 0 :(得分:1)
您的[JsonProperty]应该与JSON对象的键完全匹配。因此,您的标签类应如下所示:
public class Tags
{
[JsonProperty("Associated Team")] //this one changed
public string associatedTeam { get; set; }
public string description { get; set; }
[JsonProperty("Point of Contact")] //this one too
public string pointOfContact { get; set; }
}
通过这种方式,JSON知道将文件中实际上不存在的键映射到哪里。