How can I generate a JavaScript object literal in C#?

asp.net-mvc-4, c#, c#-4.0, json

Solution

What I think he may be asking is to convert a C# object to a JSON string.

Try this:

http://msdn.microsoft.com/en-us/library/system.json.jsonobject%28v=vs.95%29.aspx

or

http://james.newtonking.com/pages/json-net.aspx

EDIT (an example on how to use):

Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };

string json = JsonConvert.SerializeObject(product);
//{
//  "Name": "Apple",
//  "Expiry": new Date(1230422400000),
//  "Price": 3.99,
//  "Sizes": [
//    "Small",
//    "Medium",
//    "Large"
//  ]
//}

Product deserializedProduct = JsonConvert.DeserializeObject<Product>(json);

EDIT:

This is the comment from @yyamil:

You can also use anonymous objects in case you don't want to create a new class just to serialize a json object:

var notificationPayload = new
{
    notification = new
    {
        title = "Title", 
        body = "body"
    }
};

string json = JsonConvert.SerializeObject(notificationPayload);

Problem

I need to create the following JavaScript object literal in C# code, as a string, and am looking for some tips on how to best do this. ``` model: { id: "Id", fields: { Surname: { type: "string", validation: { required: true } }, FirstName: { type: "string", validation: { required: true } }, PrivateEmail: { type: "string", validation: { required: true } }, DefaultPhone: { type: "string" }, CompanyName: { type: "string" }, CreateDate: { type: "date" }, LastLoginDate: { type: "date" }, IsLockedOut: { type: "boolean" } } } ``` This defines a client side object with a model property that reflects what each row in my MVC4 view model will look like. I can use plain reflection to generate a string literal, but I would rather somehow tap into already available JSON serialization services in .NET. To do so I think I would need to create an anonymous object with properties corresponding to the JS properties above. How could I do this? EDIT: I need to loop over the properties in a view model class and generated a C# object that will serialize to a JavaScript 'transform' of the view model class similar to the one above.

Original source