如何将此JSON类型转换为C#字典

时间:2018-04-15 02:52:36

标签: c# json

        HI guys the problem is Solved with the Help Of David. I dint use his method but used Just these TWo Lines of Code. And It Works. I am Editing the Question, Which Has the Solution For this.
        I am trying to convert this JSON string to C# Dictionary<string, string> I tried several methods but no success. I want to access them as Key value pair but I cant figure out How to convert this type of JSOn with data member.

            {
              "d": "{
                \"USD\":\"0.793302\",
                \"USVCAD\":\"1.260554\",
                \"EUR\":\"0.642978\",
                \"EUVCAD\":\"1.555264\",
                \"GBP\":\"0.557200\",
                \"GBVCAD\":\"1.794687\",
                \"INR\":\"51.777115\",
                \"INVCAD\":\"0.019314\",
                \"AUD\":\"1.021391\",
                \"AUVCAD\":\"0.979057\",
                \"SPD\":\"1.040986\",
                \"SPVCAD\":\"0.960628\",
                \"SWF\":\"0.763388\",
                \"SWVCAD\":\"1.309949\",
                \"MAL\":\"3.078805\",
                \"MAVCAD\":\"0.324801\",
                \"YEN\":\"85.144672\",
                \"YEVCAD\":\"0.011745\",
                \"YUA\":\"4.975648\",
                \"YUVCAD\":\"0.200979\"
              }"
            }

I used the following code to get the above string from Browser. But when I access the Key after Serializing I get the Key as "d" and item.Value as all the Values. I want to access value for each item like USD. But when i try to call item.Value it returns string with all the values

这两行做了诀窍 - 大卫我必须创建一个单独的类才能获得价值。刚刚使用你的提示反序列化JSON两次

谢谢大家的帮助,这个问题已经解决了。我没有创建单独的类来实现这一点。

using (var wc = new WebClient())
            {
                // This Will Get the JSON Content
                var json = wc.DownloadString("http://localhost:51899/Service2.svc/GetCurrencyRates");


                //Deserialize the JSON String to Dictionary. This will return one Key = 'd' and many Values
                var values = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);

                //Deserialize the Dictionary Values. This will return one Values{ Key = Value} 
                var values2 = JsonConvert.DeserializeObject<Dictionary<string, string>>(values["d"]);

                // You need to decode JSON Twice
                MessageBox.Show(values2["USD"]);


            }

1 个答案:

答案 0 :(得分:2)

因此,您将JSON编码为另一个JSON文档中的字符串,因此您必须对其进行两次解码以获取字典:

// Add NuGet 'Newtonsoft.Json' then:

using Newtonsoft.Json;

class Data
{
    public string d;

    static Dictionary<String, String> DecodeDictionary(string json)
    {
        var data = JsonConvert.DeserializeObject<Data>(jsonString);
        return JsonConvert.DeserializeObject<Dictionary<String, String>>(data.d);

    }
}

获取您的JSON字符串并执行:

var theDictionaryYouWant = Data.DecodeDictionary(jsonString);