I know I’m probably doing something stupid, but I can’t see it. I’m trying to deserialize this JSON:
{
"SendFields":
{
"Category":
{
"value": "Request Something"
},
"email":
{
"value": "[email protected]"
}
}
}
With this class structure:
public class SendFields
{
[JsonProperty("Category")]
public KeyValuePair<string, string> Category { get; set; }
[JsonProperty("email")]
public KeyValuePair<string, string> email { get; set; }
}
public class MyData
{
[JsonProperty("SendFields")]
public KeyValuePair<string,SendFields> SendFields { get; set; }
}
But I keep getting nulls in my SendFields KVP:
I don’t know what I’m doing wrong, but maybe someone here can point me to my obvious blindness. 🙂
2
Answers
The way you have it set up currently to deserialize from json you’d need to have your json set up similar to this, each KVP property is string/string, so you need a key, and a value for each kvp property.
The matching structure can look like:
Notes:
There is convention for mapping
Dictionary<,>
to JSON object (supported by both System.Text.Json and Newtonsoft’s Json.NET) which is used for "dynamic" property names (for example you can substituteSendFields
withDictionary<string, ValueHolder>
), but not forKeyValuePair<,>
, AFAIK.I would recommend to name properties using standard conventions (i.e. Pascal case) and mark them with appropriate attributes (for Newtonsoft’s Json.NET –
JsonProperty
and for System.Text.Json –JsonPropertyName
).With original
SendFields
the following will work for Newtonsoft’s Json.NET), but not for System.Text.Json with default settings:Though I still would recommend against using
KeyValuePair<,>
here since it does not correctly represent your JSON structureConsider using online tools like https://quicktype.io/csharp or https://json2csharp.com/ to generate models for your JSON.