有没有更好的方法来做到这一点?
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();
}
Run Code Online (Sandbox Code Playgroud)
我想要的只是我的项目数组(即comp)
我发送一个像这样的json:
{ "comps" : [ { compID : 1 , compType : "t" } , { ect. } ] }
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法来做到这一点?
是的,通过定义模型:
public class MyModel
{
public IEnumerable<Comp> Comps { get; set; }
}
public class Comp
{
public int CompId { get; set; }
public string CompType { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
然后将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
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
427 次 |
| 最近记录: |