简体   繁体   中英

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?

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

JSON.NET looks for "Switches", but you might be looking for "InputRequest.Switches". Try putting "Switches" object in the global space like so:

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

And then, you can deserialize your JSON string to InputRequest object like this example:

string json = "{\"Switches\": { \"showButton\": true } }";
var myObject = JsonConvert.DeserializeObject<InputRequest>(json);

UPDATE:

Your ReadOnlyDictionary<string, bool> has no setter, you need to add a setter like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM