我有一个json字符串,如下所示
string json = "{\"Method\":\"LOGIN\",\"Skill\":{\"1\":\"SKILL-1\",\"2\":\"SKILL-2\"}}";
我正在使用JavaScriptSerializer来解析json
System.Web.Script.Serialization.JavaScriptSerializer oSerializer =
new System.Web.Script.Serialization.JavaScriptSerializer();
var dict = oSerializer.Deserialize<Dictionary<string,object>>(json);
我正在使用以下行<{1}}
Method = LOGIN
但是如何让Skill成为一个循环。喜欢
技能
MessageBox.Show("Method = "+dict["Method"].ToString());
答案 0 :(得分:1)
你应该申报自己的班级:
public class YourClassName
{
public string Method { get; set; }
public Dictionary<int, string> Skill { get; set; }
}
并反序列化Json字符串,如下所示:
var obj = oSerializer.Deserialize<YourClassName>(json);
答案 1 :(得分:1)
映射到Skill
密钥的值实际上是另一个Dictionary<string, object>
。您可以通过转换object
:
string json = "{\"Method\":\"LOGIN\",\"Skill\":{\"1\":\"SKILL-1\",\"2\":\"SKILL-2\"}}";
var oSerializer = new JavaScriptSerializer();
var dict = oSerializer.Deserialize<Dictionary<string,object>>(json);
var innerDict = dict["Skill"] as Dictionary<string, object>;
if (innerDict != null)
{
foreach (var kvp in innerDict)
{
Console.WriteLine ("{0} = {1}", kvp.Key, kvp.Value);
}
}
或者,另一种方法是将您的对象映射到适当的class
并反序列化到它而不是通用的Dictionary<string, object>
。
答案 2 :(得分:1)
假设您有以下课程
public class Data
{
public string Method { get; set; }
public Skills Skill { get; set; }
// If you don't want to use Skills class then you can use this
//public Dictionary<int, string> Skills { get; set; }
}
public class Skills
{
public int Id { get; set; }
public string Skill { get; set; }
}
因此,您可以将json
反序列化为Data
对象
Data deserializedData = JsonConvert.DeserializeObject<Data>(json);