3

I want to deserialize a Json to the following class

public class Config
{
    public String Name { get; set; }
    public SSOType Type { get; set; }
    public Dictionary<String, String> Configuration { get; set; }
}

Hence, two properties would be deserialized "as usual", and the rest would be pushed into the dictionary.

JsonConvert.DeserializeObject<Config>(filetext);

This pushs datas to properties Name and Type, but the dictionary stays empty ...

I guess the json shall look like

{
    "name":"something",
    "type":"something",
    "configuration":{
        "thing1":"value",
        "thing2":"value",
        "thing3":"value"
            }
}

but I'd like the json to be like

{
    "name":"something",
    "type":"something",
    "thing1":"value",
    "thing2":"value",
    "thing3":"value"
}

How to tweak the deserialization so it works ?

Brian Rogers
  • 125,747
  • 31
  • 299
  • 300
Paul L
  • 97
  • 9

2 Answers2

0

Would this work?

public class Config : Dictionary<string, string>
{
    public String Name { get; set; }
    public SSOType Type { get; set; }
}
peaceoutside
  • 942
  • 7
  • 12
0

Your options:

  1. JsonExtensionDataAttribute on a dictionary which will get all data for which properties are not found, and OnDesrialized callback to convert the dictionary to the format you need:

    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);
        }
    }
    
  2. Custom JsonConverter which will read JSON DOM and convert it to your class. You can find many examples on StackOverflow.

Athari
  • 33,702
  • 16
  • 105
  • 146