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();
}

私が欲しいのは、アイテムの配列(つまり、コンプ)だけです

次のような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 に答える