Search code examples
c#jsongetter-setterjson-serialization

Serialize Dictionary in C# from Json Dictionary


How to define a dictionary in JSON that can be parsed in C#?

Here's my Json that I need to parse:

  "InputRequest": 
        {
            "Switches":  {"showButton": true}
        }

Here's my example:

 public class InputRequest
{
    [JsonProperty(PropertyName="Switches")]
    public ReadOnlyDictionary<string, bool> Switches { get; }
}

For some reason it is not being able to parsed and it is showing null value for Switches parameter.

Another approach I have is to create a new parameter and take the dictionary as a string:

 public class InputRequest
{
    [JsonProperty(PropertyName="Switches")]
    public string Switches { get; }

    public ReadOnlyDictionary<string, bool> SwitchesDictionary 
    {
          var values = JsonConvert.DeserializeObject<ReadOnlyDictionary<string, bool>>(Switches);
          return values;
    }
}

For this approach, it shows error of

Unexpected character encountered while parsing value for Switches

What am I doing incorrectly here?


Solution

  • You're using a read-only collection and you've provided no setter.

    Either change your collection type to something like a normal Dictionary<string,bool> and initialize it to a collection that the deserializer can add things to, or add a set; to your property so the deserializer can set the value to a new collection it creates.

    public ReadOnlyDictionary<string, bool> Switches { get; set; }
    

    OR

    public IDictionary<string, bool> Switches { get; } = new Dictionary<string, bool>();