8

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. user@example.com",
            "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.

TruMan1
  • 33,665
  • 59
  • 184
  • 335
  • have you seen this? http://json.codeplex.com/ also... looks like elements will be a custom object unto itself which will need to also be deserialized – timothyclifford Jan 17 '11 at 23:14
  • Thx.. I'm looking at "CustomCreationConverter" from the library and also weighing using DataSets. My main concern tho is cleanly persisting the values to the database and to easily manage/modify them. – TruMan1 Jan 18 '11 at 12:54
  • @TruMan1, why havent you closed this question? Have you seen my answer below? There are other answers that could suit your problem as well.. – cnom Oct 12 '22 at 08:49

5 Answers5

3

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.

JonathanK
  • 3,000
  • 1
  • 20
  • 20
1

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.

anon
  • 4,578
  • 3
  • 35
  • 54
  • Good idea with dynamic types. Mapping it to a database would be unstructured and I image the dynamic types is slow (reflection?). Maybe DataSet and EntityFramework would be a good way to go. Instead of mapping classes, I should probably think of the schema first instead... Thx1 – TruMan1 Jan 18 '11 at 13:04
  • I started a thread for the totally opposite approach to this dilemma.. still not sure if I should map to classes or database first: http://stackoverflow.com/questions/4724465/how-to-map-json-to-sql-schema – TruMan1 Jan 18 '11 at 13:20
1

You do not need to try and create the class structure manually.

Sometimes it is rather frustrating too. :)

There is a visual studio command you can use (I think vs2015 and later):

  1. On a new class file click Menu => Edit => Paste Special
  2. Select "Paste JSON as Classes"

Now specifically in your JSON there is an error, you are missing the closing curly-brace of first "element" object.

Below is the corrected JSON:

{
  "action": "index.html",
  "method": "post",
  "elements": [
    {
      "type": "fieldset",
      "caption": "User information",
      "elements": [
        {
          "name": "email",
          "caption": "Email address",
          "type": "text",
          "placeholder": "E.g. user@example.com",
          "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"
          }
        }
      ]
    }
  ]
}

And the corresponding Classes:

public class Rootobject
{
    public string action { get; set; }
    public string method { get; set; }
    public Element[] elements { get; set; }
}

public class Element
{
    public string type { get; set; }
    public string caption { get; set; }
    public Element1[] elements { get; set; }
}

public class Element1
{
    public string name { get; set; }
    public string caption { get; set; }
    public string type { get; set; }
    public string placeholder { get; set; }
    public Validate validate { get; set; }
    public string id { get; set; }
    public string _class { get; set; }
    public Options options { get; set; }
}

public class Validate
{
    public bool email { get; set; }
    public bool required { get; set; }
    public int minlength { get; set; }
    public Messages messages { get; set; }
    public string equalTo { get; set; }
}

public class Messages
{
    public string required { get; set; }
    public string minlength { get; set; }
    public string equalTo { get; set; }
}

public class Options
{
    public string f { get; set; }
    public string m { get; set; }
}
cnom
  • 3,071
  • 4
  • 30
  • 60
0

If you just want to make sure all this unknown data gets deserialized and can be reserialized at some point in the future, I suggest the usage of IExtensibleDataObject.

Here are some samples to get you started. Hope this helps! (If you already knew this and were looking for something different...let me know!)

Forward-Compatible Data Contracts

Data Contract Versioning

Useful clarifying thread on the topic at MSDN forums

krisragh MSFT
  • 1,908
  • 1
  • 13
  • 22
0

Go to visual studio on top menu and paste your Json here enter image description here

Click on Paste Special > Paste Json As Classes, your json converted automatically into objects or classes. enter image description here