Deserializing JSON to C# - Trying to turn JSON associative array into Dictionary

后端 未结 1 1115
独厮守ぢ
独厮守ぢ 2021-01-20 12:05

I have this JSON:

{
    \"AutoRefreshEnabled\" : false,
    \"AutoRefreshInterval\" : 1,
    \"AutoCycleEnabled\" : false,
    \"AutoCycleInterval\" : 1,
            


        
相关标签:
1条回答
  • 2021-01-20 12:34

    If you want the Tabs property to be a Dictionary<string, string> then your representation in JSON is incorrect. Currently, you have:

    "Tabs" : [
        "RadTab_Home",
        "Dashboard"
    ],
    

    And it should be a string[]. If you want a mapping (i.e. Dictionary<string, string>), then you need a key to associate with the values, and therefore, a different representation in JSON:

    "Tabs" : [
        { "key1" : "RadTab_Home" },
        { "key2" : "Dashboard" }
    ],
    

    With this, you can definitely create a Dictionary<string, string>, as you would have a key to associate with the values. The key would be to create a class, like so:

    // NOTE: You can use POCO DataContract serialization for this type.
    [DataContract]
    public class Pair
    {
        [DataMember]
        public string Key { get; set; }
    
        [DataMember]
        public string Value { get; set; }
    }
    

    And then define your Tabs property like so:

    [DataMember]
    public Pair[] Tabs { get; set; }
    

    Which you can easily convert to a Dictionary<string, string> using LINQ:

    // Deserialized instance.
    MyClass instance = ...;
    
    // Map
    IDictionary<string, string> tabsMap = instance.Tabs.
        ToDictionary(p => p.Key, p => p.Value);
    

    You could add it as a method on your class, but that's a design decision for you to make (I didn't add it to the class because I assume this is a data-transfer object).

    0 讨论(0)
提交回复
热议问题