2

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)

3 Answers 3

2

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);
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

Change this

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

to

new JavaScriptSerializer().Deserialize<Mod>

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.