skip to Main Content

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:

locals window screenshot

I don’t know what I’m doing wrong, but maybe someone here can point me to my obvious blindness. 🙂

2

Answers


  1. 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.

    {
      "SendFields": {
        "Category": {
          "key": "category1",
          "value": "Request Something"
        },
        "email": {
          "key": "email1",
          "value": "[email protected]"
        }
      }
    }
    
    Login or Signup to reply.
  2. The matching structure can look like:

    public class MyData
    {
        public SendFields SendFields { get; set; }
    }
    
    public class SendFields
    {
        public ValueHolder Category { get; set; }
        public ValueHolder email { get; set; }
    }
    
    public class ValueHolder
    {
        public string value { get; set; }
    }
    

    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 substitute SendFields with Dictionary<string, ValueHolder>), but not for KeyValuePair<,>, 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:

      public class MyData
      {
          [JsonProperty("SendFields")]
          public SendFields SendFields { get; set; }
      }
      

      Though I still would recommend against using KeyValuePair<,> here since it does not correctly represent your JSON structure

    • Consider using online tools like https://quicktype.io/csharp or https://json2csharp.com/ to generate models for your JSON.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search