1

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?

3
  • 1
    What did you try? What happened? Commented Aug 30, 2013 at 13:58
  • Are you initializing the List? Commented Aug 30, 2013 at 13:59
  • What are you having trouble with? Creating the list? Having the list be serialized? Deserializing the list? Commented Aug 30, 2013 at 14:01

2 Answers 2

4

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

1 Comment

I have checked this before but I don't think I will need Json.NET for now but this works as well! Thanks
1

You need to initialize the List:

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

Then to add data:

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

1 Comment

that's it! I totally forgot to initialize it...it happens sometimes, thank you!

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.