Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

I am looking to get each "name" property and "text" property from my json string and add them to their respective lists.

JSON:

{
  "buttons": [
    {
      "name": "btnTest1",
      "text": "Click Me1!"
    },
    {
      "name": "btnTest2",
      "text": "Click Me2!"
    },
    {
      "name": "btnTest3",
      "text": "Click Me3!"
    }
  ],
  "width": 400,
  "height": 300
}

Current code:

List<string> btnName = new List<string>();
List<string> btnText = new List<string>();

public class button
{
    public string name { get; set; }
    public string text { get; set; }
}

public class Mod
{
    public List<button> buttons { get; set; }
    public int width { get; set; }
    public int height { get; set; }
}

var mod = new JavaScriptSerializer().Deserialize<List<Mod>>(json);

            foreach (Mod m in mod)
            {
                foreach (button b in m.buttons)
                {
                    btnName.Add(b.name);
                    btnText.Add(b.text);
                }
            }

But my btnName and btnText lists are not being populated.

I've tried a couple of other different solutions with no luck.

What am I doing wrong?

(the reason I don't want to use JSON.net is this application must be standalone without any dlls)

share|improve this question
up vote 2 down vote accepted

According to your json it actually represents one single Mod object. That said, the json serializer should be parsing/deserializing a Mod object instead of a list of Mod objects, you should reflect that object structure in your serialisation code as follows...

var mod = new JavaScriptSerializer().Deserialize<Mod>(json);

foreach (button b in mod.buttons)
{
     btnName.Add(b.name);
     btnText.Add(b.text);
}
share|improve this answer

You are deserializing this as a List while you have json as one object only. Try this as:

  var mod = new JavaScriptSerializer().Deserialize<Mod>(json);
share|improve this answer

Change this

new JavaScriptSerializer().Deserialize<List<Mod>>

to

new JavaScriptSerializer().Deserialize<Mod>
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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