0

有没有更好的方法来做到这一点?

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. } ] }
4

1 回答 1

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
}
于 2012-06-26T10:22:57.917 回答