nhenrique
nhenrique

Reputation: 894

Add array to a list of objects

this is the class to create my json object

    public class RootObject
    {
        public string name { get; set; }
        public string id { get; set; }
        public string school { get; set; }
        public List<object> details{ get; set; }
    }

this is the way I'm creating a new object

        var obj = new RootObject();
        obj.name= "test";
        obj.id = "null";
        obj.school = "something else";

Then I am serializing the object using JavaScriptSerializer (this is working fine) I need to add an array to this list of object "details" to get something like this:

{
  "name ":"test",
  "id":null,
  "school ":"something else",
  "details":["details1","detail2"]
}

I tried to add as string or element by element but without success. How can I solve this?

Upvotes: 1

Views: 131

Answers (2)

Paddyd
Paddyd

Reputation: 1870

You need to initialize the List:

obj.details = new List<object>();

Then to add data:

obj.details.Add("Details1");
obj.details.Add("Details2");

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1062745

I strongly suggest you just use Json.NET:

obj.details = new List<object>
{
    "details1", "details2"
};

Then, JsonConvert.SerializeObject(obj, Formatting.Indented) gives:

{
  "name": "test",
  "id": "null",
  "school": "something else",
  "details": [
    "details1",
    "details2"
  ]
}

Upvotes: 4

Related Questions