一尘不染

如何将JSON转换为C#类?

json

我有一个想要表示为C#类的复杂JSON对象。我在名为“ Form”的父类上有一个良好的开端,但是如何代表不同类型的集合(请参见下面的“
elements”对象)?

这是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"
            }
        }
    ]
]
}

我开始的课程看起来像这样:

public class Form
{
    public Guid id
    {
        get;
        set;
    }

    public string action
    {
        get;
        set;
    }

    public string method
    {
        get;
        set;
    }

    public ??? elements
    {
        get;
        set;
    }

    public Form()
    {

    }
}

如何处理“ elements”属性以获得所需的JSON输出?

我正在WCF 4.0和web.config中的以下属性一起使用:automaticFormatSelectionEnabled =“
false”,defaultOutgoingResponseFormat =“ Json”。任何帮助或想法将不胜感激。


阅读 224

收藏
2020-07-27

共1个答案

一尘不染

哇。有趣的问题。也许使用ExpandoObject /动态?

http://msdn.microsoft.com/zh-
CN/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

或者我认为匿名类型可以使用内置的.NET JSON序列化程序进行序列化。

2020-07-27