分隔的属性名称反序列化JSON

分隔的属性名称反序列化JSON

本文介绍了用'空格'分隔的属性名称反序列化JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to deserialize a json which has got property names with a 'space' in between them ('Associated Team' and 'Point of Contact'). I have tried deserializing the json string by creating a strongly typed object but it is unable to map these 2 properties.

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": "[email protected]"
  }
}

.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进行反序列化,但是由于两个属性之间的名称之间有空格,因此我又无法获取这两个属性的值.

I have also tried deserializing the json dynamically(below) but then again I am unable to get the values of the two properties because they have got space in between their names.

dynamic deserializedResourceGroupDetails = JsonConvert.DeserializeObject(jsonString)));

推荐答案

您的[JsonProperty]应该与JSON对象的键完全匹配.因此,您的标签类应如下所示:

Your [JsonProperty] should exactly match the key of your JSON object. So your Tags class should look like this:

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知道将文件中真正不存在的键映射到何处.

This way, JSON knows where to map those keys in your file that aren't literally in your code.

这篇关于用'空格'分隔的属性名称反序列化JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 11:07