0

Is there a nicer way to do this?

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

All I want is my array of items (i.e. comp)

I am sending a json like this:

{ "comps" : [ { compID : 1 , compType : "t" } , { ect. } ] }
1

1 Answer 1

7

Is there a nicer way to do this?

Yes, by defining models:

public class MyModel
{
    public IEnumerable<Comp> Comps { get; set; }
}

public class Comp
{
    public int CompId { get; set; }
    public string CompType { get; set; }
}

and then deserialize the JSON string to this model so that you can work with strong types, not some dictionaries of magic strings:

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
}
1
  • note for the reader - the names in the model and the json need to be exactly the same (i tried to change and poof), and i believe that the reason using capitals is cuz its props that actually create a var with the same name non capital am i right about that? Jun 26, 2012 at 10:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.