Reputation: 894
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
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
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