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)));
JSON is a format that encodes objects in a string. Serialization means to convert an object into that string, and deserialization is its inverse operation (convert string -> object).
JsonPropertyAttribute indicates that a property should be serialized when member serialization is set to opt-in. It includes non-public properties in serialization and deserialization. It can be used to customize type name, reference, null, and default value handling for the property value.
Deserializes the JSON to the specified . NET type. Deserializes the JSON to the specified . NET type using a collection of JsonConverter.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With