有更好的方法吗?
JavaScriptSerializer jss = new JavaScriptSerializer();
Dictionary<string, object> dic =
jss.Deserialize<Dictionary<string, object>>(json);
Dictionary<string, object>.Enumerator enumerator = dic.GetEnumerator();
enumerator.MoveNext();
ArrayList arr = (ArrayList)enumerator.Current.Value;
foreach (Dictionary<string, object> item in arr)
{
string compID = item["compID"].ToString();
string compType = item["compType"].ToString();
}
我想要的只是我的项目数组(即comp)
我发送的是这样的json:
{ "comps" : [ { compID : 1 , compType : "t" } , { ect. } ] }
答案 0 :(得分:7)
有更好的方法吗?
是的,通过定义模型:
public class MyModel
{
public IEnumerable<Comp> Comps { get; set; }
}
public class Comp
{
public int CompId { get; set; }
public string CompType { get; set; }
}
然后将JSON字符串反序列化为此模型,以便您可以使用强类型,而不是魔术字符串的一些字典:
JavaScriptSerializer jss = new JavaScriptSerializer();
MyModel model = jss.Deserialize<MyModel>(json);
foreach (Comp comp in model.Comps)
{
// Do something with comp.CompId and comp.CompType here
}