Destroy JSON in a dictionary
I want to deserialize Json for the following class
public class Config
{
public String Name { get; set; }
public SSOType Type { get; set; }
public Dictionary<String, String> Configuration { get; set; }
}
Therefore, two properties will be deserialized "as usual" and the rest will be placed in the dictionary.
JsonConvert.DeserializeObject<Config>(filetext);
This clicks on the Name and Type properties, but the dictionary remains empty ...
I think the json will look like
{
"name":"something",
"type":"something",
"configuration":{
"thing1":"value",
"thing2":"value",
"thing3":"value"
}
}
but I would like the json to be like
{
"name":"something",
"type":"something",
"thing1":"value",
"thing2":"value",
"thing3":"value"
}
How do I set up deserialization to work?
source to share
Your options:
-
JsonExtensionDataAttribute
in the dictionary, which will receive all data for which no properties were found, and aOnDesrialized
callback to convert the dictionary to the desired format:public class Config { public String Name { get; set; } [JsonIgnore] public Dictionary<string, string> Configuation { get; set; } [JsonExtensionData] private Dictionary<string, JToken> _configuration; [OnDeserialized] private void Deserialized (StreamingContext context) { Configuation = _configuration.ToDictionary(i => i.Key, i => (string)i.Value); } }
-
A custom
JsonConverter
one that will read the JSON DOM and convert it to your class. You can find many examples on StackOverflow.
source to share