简体   繁体   English

在c#中将JSON字符串转换为Dictionary

[英]Convert JSON string to Dictionary in c#

I have a json string like 我有一个json字符串

{
    "action":"postRecord", 
     "data":{
            "0":{
                  "lid":999,
                   "cid":1234
                 },
            "1":{
                  "lid":111,
                  "cid":"6789"
                 }
        }
}

and

i want it co convert to Dictionary object so that i can get the data and iterate over it like data[0][lid] = 999 data[0][cid] =1234 data[1][lid] = 111 data[1][cid] = 6789 我希望它可以转换为Dictionary对象,这样我就可以得到data并像data[0][lid] = 999一样迭代它data[0][lid] = 999 data[0][cid] =1234 data[1][lid] = 111 data[1][cid] = 6789

The problem is that i have to use ONLY Native Libraries of .net and I have version 2.0 问题是我必须使用ONLY Native Libraries of .net and I have version 2.0

You can do 你可以做

Dictionary<string, object> obj = JsonConvert.DeserializeObject<Dictionary<string, object>>(Convert.ToString(data));

using JSON.NET 使用JSON.NET

If you can use .NET 3.5 (I was not sure whether your restriction to .NET 2.0 may be extended to 3.5) then this other question on the same topic has this great answer : 如果你可以使用.NET 3.5 (我不确定你对.NET 2.0的限制是否可以扩展到3.5)那么关于同一主题的另一个问题这个很好的答案

string json = @"{ ""id"": 13, ""value"": 255 }";

var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();

var dict = serializer.Deserialize<Dictionary<string, int>>(json);

You need to add a reference to System.Web.Extensions to use that class. 您需要添加对System.Web.Extensions的引用才能使用该类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM