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.
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):
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: