I have a complex JSON object that I want represent as C# class. I have a head start on the parent class called "Form", but how can I represent a collection for different types (see the "elements" object below)?
Here is the JSON object:
{
"action": "index.html",
"method": "post",
"elements":
[
{
"type": "fieldset",
"caption": "User information",
"elements":
[
{
"name": "email",
"caption": "Email address",
"type": "text",
"placeholder": "E.g. [email protected]",
"validate":
{
"email": true
}
},
{
"name": "password",
"caption": "Password",
"type": "password",
"id": "registration-password",
"validate":
{
"required": true,
"minlength": 5,
"messages":
{
"required": "Please enter a password",
"minlength": "At least {0} characters long"
}
}
},
{
"name": "password-repeat",
"caption": "Repeat password",
"type": "password",
"validate":
{
"equalTo": "#registration-password",
"messages":
{
"equalTo": "Please repeat your password"
}
}
},
{
"type": "radiobuttons",
"caption": "Sex",
"name": "sex",
"class": "labellist",
"options":
{
"f": "Female",
"m": "Male"
}
}
]
]
}
The class I have start looks like this:
public class Form
{
public Guid id
{
get;
set;
}
public string action
{
get;
set;
}
public string method
{
get;
set;
}
public ??? elements
{
get;
set;
}
public Form()
{
}
}
How do I handle the "elements" property to get the desired JSON output?
I am using WCF 4.0 with these atributes in the web.config: automaticFormatSelectionEnabled="false", defaultOutgoingResponseFormat="Json". Any help or ideas would be greatly appreciated.
Wow. Fascinating question. Maybe use ExpandoObject / dynamic?
http://msdn.microsoft.com/en-us/library/system.dynamic.expandoobject.aspx
http://blogs.msdn.com/b/csharpfaq/archive/2009/10/01/dynamic-in-c-4-0-introducing-the-expandoobject.aspx?PageIndex=4
Or anonymous types I think are serializable with the built-in .NET JSON serializer.
If you don't have the liberty of using dynamic types from .NET 4 or would like to leverage the benefits that static typing provide, the JSON Class Generator project on codeplex will generate c# classes given a json input string. (shameless plug) I've also taken code from this project and slapped a web UI on it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With