views:

39

answers:

3

Can we do something like this or something similar?

var staffs = {
               "Staff": 
               [
                { "ID" : 1, "Name" : "John" },
                { "ID" : 2, "Name" : "Mark"}
               ]
            };

foreach (var staff in staffs)
{
    Console.WriteLine("ID: {0}", staff.ID);
    Console.WriteLine("Name: {0}", staff.Name);
}



Instead of this long code:

public class Test
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Page.IsPostBack)
            return;

        List<Staff> staffs = new List<Staff>()
        {
            new Staff() {ID = 1, Name = "John"},
            new Staff() {ID = 2, Name = "Mark"}
        };

        foreach (var staff in staffs)
        {
            Console.WriteLine("ID: {0}", staff.ID);
            Console.WriteLine("Name: {0}", staff.Name);
        }
    }
}

public class Staff
{
    public int ID { get; set; }
    public string Name { get; set; }
}

I tried but Visual Studio shows syntax error.

+1  A: 

Nope. What you've demonstrated is the allowed syntax for collection and object initializers.

If you're trying to shorten it somewhat you could drop the trailing () off of each initializer, such as:

var list = new List<Staff>
{
    new Staff {ID = 1, Name = "John"},
    new Staff {ID = 2, Name = "Mark"}
}
Ahmad Mageed
A: 

You can make it shorter but not exactly like JSON.

List<Staff> staffs = new List<Staff>()
{
    new Staff() {ID = 1, Name = "John"},
    new Staff() {ID = 2, Name = "Mark"}
};

...can you turn into: (This is an array not a List<T> but you can wrap it)

var staffs = new[]
{
    new Staff {ID = 1, Name = "John"},
    new Staff {ID = 2, Name = "Mark"}
};
lasseespeholt
This is the shortest we can get, thanks!
Lee Sy En
A: 

The closest you can get is:

var staffs = new List<Staff> {
                new Staff{ ID : 1, Name : "John" },
                new Staff{ ID : 2, Name : "Mark"}

            };

foreach (var staff in staffs)
{
    Console.WriteLine("ID: {0}", staff.ID);
    Console.WriteLine("Name: {0}", staff.Name);
}

Note: member names and values are not quoted, but strongly typed (unlike json).

You might be able to deserialize a JSON representation directly to the object graph using a Json serializer.

Oded