JSON array to C# Dictionary

后端 未结 6 1333
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-19 14:04

How do I convert a JSON array like this

[{\"myKey\":\"myValue\"},
{\"anotherKey\":\"anotherValue\"}]

to a C# Dictionary wi

相关标签:
6条回答
  • 2020-12-19 14:12

    Maybe converting to array of KeyValuePairs will help

    using System.Linq;
    
    var list = JsonConvert.DeserializeObject<IEnumerable<KeyValuePair<string, string>>>(jsonContent);
    var dictionary = list.ToDictionary(x => x.Key, x => x.Value);
    
    0 讨论(0)
  • 2020-12-19 14:21

    The data must to be sent as follows (format):

    "Values": [
      {"Key" : "abc"  , "Value": 23.14},
      {"Key" : "abc1" , "Value": 23.11},
      {"Key" : "abc2" , "Value": 23.17},
      {"Key" : "abc3" , "Value": 23.19}
    ]
    

    thereby, the converting process will work. It worked fine to me in my attempt to convert from JSON to dictionary<string,decimal>

    0 讨论(0)
  • 2020-12-19 14:22

    For anyone interested - this works, too:

    Example JSON:

    [{"device_id":"VC2","command":6,"command_args":"test args10"}, {"device_id":"VC2","command":3,"command_args":"test args9"}]

    C#:

    JsonConvert.DeserializeObject<List<JObject>>(json)
                .Select(x => x?.ToObject<Dictionary<string, string>>())
                .ToList()
    
    0 讨论(0)
  • 2020-12-19 14:22

    I found that using a list of KeyValuePairs didn't work. I got the right number of elements but they had null Keys and Values.

    In the end the only solution that worked for me was deserialising to a list of dictionaries (which each had a single kvp element).

    0 讨论(0)
  • 2020-12-19 14:29

    Since you can only deserialize from an object, do just that by manipulating the JSON string a little first. Wrap it in an object:

    json = String.Format("{{\"result\":{0}}}", json);
    
    0 讨论(0)
  • 2020-12-19 14:30

    Its quite simple actually :

    lets say you get your json in a string like :

    string jsonString = @"[{"myKey":"myValue"},
    {"anotherKey":"anotherValue"}]";
    

    then you can deserialize it using JSON.NET as follows:

    JArray a = JArray.Parse(jsonString);
    
    // dictionary hold the key-value pairs now
    Dictionary<string, string> dict = new Dictionary<string, string>();
    
    foreach (JObject o in a.Children<JObject>())
    {
        foreach (JProperty p in o.Properties())
        {
            string name = p.Name;
            string value = (string)p.Value;
            dict.Add(name,value);
        }
    }
    
    0 讨论(0)
提交回复
热议问题