【问题标题】:Deserializing JSON with 'space' separated property names使用“空格”分隔的属性名称反序列化 JSON
【发布时间】:2018-11-06 10:15:48
【问题描述】:

我需要反序列化一个 json,它的属性名称之间有一个“空格”(“关联团队”和“联系点”)。我尝试通过创建强类型对象来反序列化 json 字符串,但它无法映射这两个属性。

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代码sn-p:

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))); 

【问题讨论】:

  • 应该JsonProperty() 属性有"Associated Team" 而不是"associatedTeam""pointOfContact" 也一样。
  • 是的,成功了。我更改了类似于 json 字符串的实际属性名称的 JsonProperty 属性并且有效。谢谢!
  • 您也可以在没有空格的情况下命名您的 json 的属性,并将您的 Tags 类的属性命名为您的 json。那么你就不必使用 [JsonProperty()] 注释了。

标签: c# asp.net


【解决方案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 知道将文件中那些不在代码中的键映射到哪里。

【讨论】:

    猜你喜欢
    • 2019-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-14
    相关资源
    最近更新 更多