The Inquisitive Coder
The Inquisitive Coder

Reputation: 1315

Deserializing JSON with 'space' separated property names

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 string: (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 code snippet:

var deserializedResourceGroupDetails = JsonConvert.DeserializeObject<AzureResourceData>(jsonString);

AzurResourceData.cs class:

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

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

Upvotes: 6

Views: 6462

Answers (1)

Maaike Brouwer
Maaike Brouwer

Reputation: 184

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

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

Upvotes: 7

Related Questions