JSON array to C# Dictionary

后端 未结 6 1337
佛祖请我去吃肉
佛祖请我去吃肉 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: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 dict = new Dictionary();
    
    foreach (JObject o in a.Children())
    {
        foreach (JProperty p in o.Properties())
        {
            string name = p.Name;
            string value = (string)p.Value;
            dict.Add(name,value);
        }
    }
    

提交回复
热议问题